1

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

1
  • What is the error exactly and where does it occur? Commented Sep 28, 2016 at 6:18

1 Answer 1

2

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
    }

}
Sign up to request clarification or add additional context in comments.

1 Comment

literally stack overflow is a better place bcoz of u guys

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.