Search code examples
recursionsearchbinary-search

Bug in recursive binary search method?


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};

Solution

  • There are 2 problems I can see:

    1. In the second recursive call, you're passing mid for the left bound and left for the right bound. That doesn't seem right.
    2. If you search for the last Person, the calculation of mid never advances, and left never equals right, so it recurses infinitely.