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;
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With