In: Computer Science
binarySearchLengths(String[] inArray, String search, int start, int end)
This method will take in a array of strings that have been sorted in order of increasing length, for ties in the string lengths they will be in alphabetical order. The method also takes in a search string and range of indexes (start, end). The method will return a String formatted with the path of search ranges followed by a decision (true or false), see the examples below.
Example 1: binarySearchLengths({"a","aaa","aaaaa"},"bb",0,2) would return the string "(0,2) (0,0) False" This means the method first looked in the range 0 to 2, then made a recursive call to the range 0 to 0, then made the determiniation that the element was not in the array "False".
Example 2: binarySearchLengths({"a","b","c","d","e","f","g"},"e",0,6) would return the string "(0,6) (4,6) (4,4) True" This means the method first looked in the range 0 to 6, then made a recursive call to the range 4 to 6, then made a recursive call to the range 4 to 4, then made the determiniation that the element was in the array "True".
Java code
public class T{
public static String binarySearchLengths(String[] inArray, String search, int start, int end){
String Answer = "";
boolean found = false;
while(start <= end){
Answer +="("+ Integer.toString(start) +","+ Integer.toString(end) + ") ";
int mid = (start + end)/2;
if(inArray[mid].compareTo(search) == 0){
found = true;
break;
}
else if(inArray[mid].length() > search.length()) end = mid - 1;
else if (inArray[mid].compareTo(search) < 0) start = mid + 1;
else end = mid-1;
}
if(found) Answer+="True";
else Answer+="False";
return Answer;
}
public static void main(String []args){
String [] Array = {"a","aaa","aaaaa"};
System.out.println(binarySearchLengths(Array,"bb",0,2));
String []Array2 = {"a","b","c","d","e","f","g"};
System.out.println(binarySearchLengths(Array2,"e",0,6));
}
}