I am trying to write a method to perform binary search on an array of persons. The method should return the index that the person is found at, or -1 if it doesn't exist. For some reason, the method seems to return -1 even when the person is in the array. Please help I am a beginner.
public static int binarySearchRecursive(Person[] a, Person p) {
int right = a.length -1;
int left = 0;
return binarySearchRecursive(a, p, left, right);
}
private static int binarySearchRecursive(Person[] a, Person p, int left, int right) {
int mid = (left + right) / 2;
if (a[mid].compareTo(p) == 0)
return mid;
if (left == right)
return -1;
else {
if (a[mid].compareTo(p) > 0) {
return binarySearchRecursive(a, p, left, mid);
}
else {
return binarySearchRecursive(a, p, mid, left);
}
}
}
public static void main(String[] args) {
Person s = new Person("shlomo",13);
Person m = new Person("menachem",15);
Person y = new Person("yehuda",18);
Person a = new Person("atara",20);
Person [] array = {s, m, y, a};
There are 2 problems I can see:
mid
for the left bound and left
for the right bound. That doesn't seem right.Person
, the calculation of mid
never advances, and left
never equals right
, so it recurses infinitely.