0

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);
}
C. Suarez
  • 11
  • 1
  • 5

1 Answers1

0

Make sure you're clear about what the algorithm does, and then take a good long look at your recursive calls.

Edward Peters
  • 3,623
  • 2
  • 16
  • 39