Ketan G
Ketan G

Reputation: 517

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

Upvotes: 1

Views: 53

Answers (1)

nem035
nem035

Reputation: 35491

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
    }

}

Upvotes: 2

Related Questions