1

I need help with implementing the binary search algorithm, can someone tell me what's wrong with my code:

public int bsearch(Item idToSearch) { 
    int lowerBoundary = 0;
    int upperBoundary = myStore.size() - 1;
    int mid = -1;

    while(upperBoundary >= lowerBoundary) {
        mid = (lowerBoundary + upperBoundary) / 2;

        //if element at middle is less than item to be searched, than set new lower boundary to mid
        if(myStore.get(mid).compareTo(idToSearch) < 0) {
            lowerBoundary = mid - 1;
        } else {
            upperBoundary = mid + 1;
        }
    } //end while loop

    if(myStore.get(mid).equals(idToSearch)) {
        return mid;
    } else {
        return -1; // item not found
    }
} // end method
2
  • 3
    A debugger could definitely tell you what is wrong. Commented Mar 31, 2014 at 1:42
  • 1
    a quite incorrect algorithm... Commented Mar 31, 2014 at 1:46

3 Answers 3

4

I think you made a mistake when update lowerBoundary and upperBoundary.

It may be:

    if(myStore.get(mid).compareTo(idToSearch) < 0){
        lowerBoundary = mid + 1;
    } else {
        upperBoundary = mid - 1;
    }

And why don't you break the loop if you find the element at mid?

Sign up to request clarification or add additional context in comments.

Comments

0

I would

  • stop when the lower and upper bound are the same.
  • stop when you find a match
  • use mid = (hi + lo) >>> 1; to avoid an overflow causing a bug.
  • read the code in the JDK which does this already as it works correctly.

Comments

0

The first issue is with the boundaries, also you should stop in case he found the value, but he doesn't which lead to possible overlook.

while(upperBoundary >= lowerBoundary)
{
        mid = (lowerBoundary + upperBoundary) / 2;

        if (myStore.get(mid).equals(idToSearch)) break; // goal

        if(myStore.get(mid).compareTo(idToSearch) < 0)
        {
            lowerBoundary = mid + 1;
        }
        else
        {
            upperBoundary = mid - 1;
        }
}

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.