Apart from adding return to the recursive calls of binarySearch, there are a couple of flaws in the logic:
mid should be decremented to catch values in the left part:
return binarySearch(searchFor, inArray, from, --mid);
- there should be a check for valid
mid, from, to values to fit inside the input array
Thus, the method should look as:
public static int binarySearch(int searchFor, int[] inArray, int from, int to) {
if (to >= from && from > -1 && to <= inArray.length) {
int mid = (to-from)/2 + from;
if (mid >= inArray.length) {
return -1;
}
// System.out.printf("from=%d to=%d mid=%d val=%d%n", from, to, mid, inArray[mid]); // debug print
if (inArray[mid] == searchFor) {
return inArray[mid];
} else if (inArray[mid] < searchFor){
return binarySearch(searchFor, inArray, ++mid, to);
} else {
return binarySearch(searchFor, inArray, from, --mid);
}
}
return -1;
}
}
Tests:
public static int binarySearch(int searchFor, int... inArray) {
System.out.printf("Searching for %d in %s%n", searchFor, Arrays.toString(inArray));
return binarySearch(searchFor, inArray, 0, inArray.length);
}
System.out.println(binarySearch(10));
System.out.println(binarySearch(10, 10));
System.out.println(binarySearch(10, 1));
System.out.println(binarySearch(10, 0, 1, 5, 8, 10, 21));
System.out.println(binarySearch( 0, 0, 1, 5, 8, 10, 21));
System.out.println(binarySearch(21, 0, 1, 5, 8, 10, 21));
System.out.println(binarySearch(10, 0, 1, 3, 5, 8, 10, 21));
System.out.println(binarySearch( 0, 0, 1, 5, 8, 10, 15, 21));
System.out.println(binarySearch(21, 0, 1, 5, 8, 10, 16, 21));
System.out.println(binarySearch(30, 0, 1, 5, 8, 10, 21));
System.out.println(binarySearch(-1, 0, 1, 5, 8, 10, 21));
System.out.println(binarySearch(7, 0, 1, 5, 8, 10, 21));
Output:
Searching for 10 in []
-1
Searching for 10 in [10]
10
Searching for 10 in [1]
-1
Searching for 10 in [0, 1, 5, 8, 10, 21]
10
Searching for 0 in [0, 1, 5, 8, 10, 21]
0
Searching for 21 in [0, 1, 5, 8, 10, 21]
21
Searching for 10 in [0, 1, 3, 5, 8, 10, 21]
10
Searching for 0 in [0, 1, 5, 8, 10, 15, 21]
0
Searching for 21 in [0, 1, 5, 8, 10, 16, 21]
21
Searching for 30 in [0, 1, 5, 8, 10, 21]
-1
Searching for -1 in [0, 1, 5, 8, 10, 21]
-1
Searching for 7 in [0, 1, 5, 8, 10, 21]
-1
else ifcallsreturns, you also miscalculate the upper bound when you go left: You wantmid - 1here. (And I think you should return the index,mid, instead of the valueinArray[mid], which you already know.)