Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is wrong with my Binary Search algorithm implementation?

Tags:

java

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;
}
like image 268
NovaScot Avatar asked Dec 02 '25 18:12

NovaScot


1 Answers

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.

like image 112
Ganz7 Avatar answered Dec 04 '25 08:12

Ganz7