2

I'm confused at exactly where this happens. I've traced this simple code out on paper as well as used the computer but I can't figure out. In my example I created an array of {1, 2, 3, 4, 5} and it came up with this error for numbers 4 and 5. It worked fine for numbers 1, 2, and 3, as well as numbers not in the array. Can anyone help, please?

public static int search(int[] ar, int num)
{
    int low=0;
    int hi=ar.length-1;
    int mid=(low+hi/2);
    while(hi>=low || mid<=low || mid>=hi )
    {
        if(ar[mid]==num)
        {
            return mid;
        }
        else if(ar[mid]>num)
        {
            hi=mid-1;
            mid=(low+hi/2);
        }
        else
        {
            low=mid+1;
            mid=(low+hi/2);
        }
    }
    return -1;
}
5
  • How about you use the debugger to trace it out for real? Commented Mar 18, 2012 at 20:16
  • any chance you could post on which line the out-of-bounds is occurring? Commented Mar 18, 2012 at 20:16
  • Are you sure about coniditions mid <= low ? May be mid <= hi && mid >= low ? Commented Mar 18, 2012 at 20:19
  • put in a lot of prints and see how your code is going along in decisions. Commented Mar 18, 2012 at 20:20
  • changing the or to and didn't change anything. And can you clarify that, j13r? What exactly do you mean? Commented Mar 18, 2012 at 20:27

2 Answers 2

3
mid=(low+hi/2);

You need to use prantheses so that you divide after adding low and hi.

mid=(low+hi) / 2;

Also your loop condition should not allow mid to be >high because then it won't termintate for large number not in the array.

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

2 Comments

Thanks for pointing this out! I always seem to miss the stupidest little things. But now it can't find the highest number? I'll go see if I made any other stupid mistakes.
@frozenxdreamer As suggested by others try adding few print statements and see the execution of program that will help more than mentally tracing the steps. You can also make use of debugger of your IDE.
0

The problem is the condition under which you continue looping. Try changing this:

while (hi>=low || mid<=low || mid>=hi) {

to this:

while (hi>=low) {

If hi < low, you do not want to continue the loop regardless of the other two conditions (one of which will always be true, I think, if hi < low).

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.