1

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

2
  • doesn't integer division always truncate the remainder? In that case middle + 1 would never become greater than last Commented Jul 7, 2015 at 15:10
  • 1
    Your statement in else if should be last = middle -1; Not first. Commented Jul 7, 2015 at 15:11

1 Answer 1

3

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

else if(obj.compareTo(array[middle]) < 0) last = middle - 1;
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.