Help me. I am a newbie to java and I am stuck in binary search recursion (stackoverflow error) and I can't find solution anywhere.
public class BinarySearch {
public static int binAry (int ary[], int st, int lt, int val){
if (st<=lt) {
int mid = (st + (lt-st)) / 2;
if (val > ary[mid]) {
binAry(ary, mid+1, lt, val);
}
else if (val < ary[mid]) {
binAry(ary, st, mid-1, val);
}
else{
return mid;
}
}
return -1;
}
public static void main (String[] args){
BinarySearch bs = new BinarySearch();
int [] numbers = {0,1,2,3,4,5};
int x = 3;
int pt = numbers.length;
int p = bs.binAry(numbers, 0, pt-1, x);
if (p == -1){
System.out.println("Number not found.");
}
else{
System.out.println("Number found at " + p);
}
}
}
binAry(...)withreturn binAry(...)when you call it recursively. Otherwise, you will returnmidwhen the element is the middle of original array, and -1 in all other cases.standlt(st +lt -st) / 2is always(lt) / 2;. I assume that is not what u meant.