3

I apologize for asking such a simple question. But I'm stumped. I think I've implemented the solution using the correct algorithm but for some reason I'm getting a stackoverlow error when I run this. Any help?

public class BinarySearch {
public static void main(String[] args){
    int[] a = new int[]{1,3,5,9,10,100,210,423,500};
    System.out.println(binarySearch(a,5,0,a.length-1));
}
static int binarySearch(int a[], int x, int left, int right){
    if(left>right)
        return -1;
    int mid = left+right/2;

    if(a[mid] < x){
        return binarySearch(a,x,mid+1,right);
    }
    else if (a[mid] > x){
        return binarySearch(a,x,left,mid-1);
    }
    return mid;
}
2
  • 1
    What exact error are you getting? Can you post your console output? Commented Aug 13, 2015 at 7:34
  • 4
    You are missing parentheses around int mid = left+right/2;. Should be int mid = (left+right)/2;. Commented Aug 13, 2015 at 7:35

1 Answer 1

2

When you're calculating the value for mid, your scope is not proper.

int mid = left+right/2

vs

int mid = (left+right)/2

While this is a simple solution to your problem, you should also checkout Peter's and Laune's suggestions. They both handle integer overflows.

If the length of the array is equal to or close to the max value of the int datatype in Java, you might run into some issues.

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

17 Comments

ideally int mid = (left + right) >>> 1 to avoid overflows ;) +1
@PeterLawrey I prefer mid = left + (right-left)/2 but this is a matter of taste (for me: as it avoids the language specific operator)
@PeterLawrey Can you ever have an array where left+right overflows? Got a program to prove it?
Use int mid= (left + right)/2 that will give correct algorithm
@Mishax see my previous comment. It's the sum that overflows, not the division.
|

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.