0

I'm feeling very very stupid because I've solved much harder stuff than this. This is supposed to be an implementation of ordered binary search. Whenever I trace the 12, a stackoverflow error pops up. Any help please?

public class binarySearch {        
    public static void main(String[] args) {
        int[] arr = { 1, 5, 6, 8, 12, 88 };
        System.out.println(binaryHelper(0, arr.length - 1, 12, arr));
    }

    public static int binaryHelper(int first, int last, int target, int[] arr) {
        if(first > last) return -1;
        else {
            int mid = first + last / 2;
            if(arr[mid] == target) return mid;
            else if(arr[mid] > target) return binaryHelper(first, mid - 1, target, arr);
            else return binaryHelper(mid + 1, last, target, arr);
        }
    }
}
2
  • possible duplicate of Java BinarySearch Commented Sep 13, 2014 at 11:24
  • How do you think first+last/2; is evaluated? Commented Sep 13, 2014 at 11:30

2 Answers 2

2

This is due to the precedence order of your operators in your mid variable computation. It should be computed as:

int mid = (first + last) / 2;

instead of

int mid = first+last/2;
Sign up to request clarification or add additional context in comments.

Comments

1

Error is here:

 int mid = first+last/2;

this means mid is equal to first + last dividied by 2 which is wrong

so it should be like

int mid = (first+last)/2;

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.