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;
}
int mid = left+right/2;. Should beint mid = (left+right)/2;.