0
public static void main(String[] args) {
    int [] arr = {11,14,18,22,36,89,125};
    System.out.println(recursive_binary_search(arr,0,arr.length,989));

}


public static int recursive_binary_search(int[] A,int p,int r,int x) {

    if( p > r) {

        return -1;
    }else {
        int q=(p+r)/2;
        if(A[q]==x) {

            return q;
        }else if(A[q]>x) {

            return recursive_binary_search(A,p,q-1,x);
        }else {
            return recursive_binary_search(A,q+1,r,x);

        }


    }


}

Hey, thank you for reading. I am having some problem with this recursive binary search method. When I try to search something that is not in the array, java give me "Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 7".

I thought it should return -1 because of the p>r condition. I tried to change the condition to p>=r but then it would return -1 for things that are actually present in array. What am I doing wrong? Thank you so much

1 Answer 1

1

Your search should start with 0 to arr.length-1,

System.out.println(recursive_binary_search(arr,0,arr.length-1,989));
Sign up to request clarification or add additional context in comments.

Comments

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.