I need to implement a recursive binary search algorithm for an integer array sorted in ascending order (i.e 1,2,3,4...
).
The array I have contains the following numbers:
0 0 0 0 0 0 0 1 2 2 3 3 3 3 5 6 7 7 7 9
However, my current implementation of binary search only finds the numbers to the right of 3. For some reason, it doesn't find 9, 7, 6, and 5.
below is my code:
private int srchHelper(int[] array, int first, int last, int x) {
if (first > last) return - 1;
int mid = (first + last) / 2;
if (array[mid] == x) {
return mid;
}
if (array[mid] < x) {
return srchHelper(array, (mid + 1), last, x);
}
else return srchHelper(array, (mid - 1), last, x);
}