Ketan G Ketan G - 2 months ago 16
Java Question

Compile time error in Binary Search Recursive implementation

I am getting one compilation error in binary search recursive implementation

Here is my method:

public static int binarySearch(int[] a, int start, int end, int x) {
if (start > end) {
return -1;
}
int mid = (start + end) / 2;
if (a[mid] == x) {
return mid;
} else if (a[mid] > x) {
binarySearch(a, start, mid - 1, x);
} else {
binarySearch(a, mid + 1, end, x);
}
}


I am giving two base case for this and returning two int values, but still i am getting error why this is happening . Any related thoughts'd be apprecited.

Thanks

Answer

What do you think gets returned on the first call if both start > end and a[mid] == x are false?

You need to return your recursive calls as well so that the found value (or -1) will propagate back through the recursion stack frames:

public static int binarySearch(int[] a, int start, int end, int x) {
    if (start > end) {
        return -1;
    }
    int mid = (start + end) / 2;
    if (a[mid] == x) {
        return mid;
    } else if (a[mid] > x) {
        return binarySearch(a, start, mid - 1, x); // return here
    } else {
        return binarySearch(a, mid + 1, end, x);   // return here
    }

}