rshah
rshah

Reputation: 691

While loop doesnt end in iterative binary search

I'm currently writing a binary search that uses iteration instead of recursion and its not returning anything. I've debugged it down to the while loop not ending but I can't seem to figure out where I went wrong.

Here is the code:

public static <E extends Comparable> boolean binarySearchIterative(E[] array, E obj) {
    int first = 0;
    int last = array.length - 1;
    while(first <= last) {
        int middle = (first + last) / 2;
        if(array[middle].equals(obj)) return true;
        else if(obj.compareTo(array[middle]) < 0) first = middle - 1;
        else first = middle + 1;
    }
    return false;
}

And yes, my list is ordered ;)

Upvotes: 1

Views: 191

Answers (1)

Anand S Kumar
Anand S Kumar

Reputation: 90889

In the second else if part you need to set last instead of first -

else if(obj.compareTo(array[middle]) < 0) last = middle - 1;

Upvotes: 3

Related Questions