0

I have a bug in this binary search code that I can't get to the bottom of. Sometimes the code works, and sometimes it just goes into an endless loop. I think I must be close, but any tips where I am going wrong would be appreciated. Thanks in advance.

bool search(int value, int values[], int n)
{

//binary search

int min = 0;
int max = n - 1;
int middle;

while(min <= max) {
    middle = (max - min)/2;
    if(values[middle] == value){
        return true;
    }

    else if (values[middle] > value){
        max = middle-1;
    }

    else {
        min = middle+1;
    }
}
return false;
}
1

Shouldn't the middle be (max+min) / 2?

If the max is 5 and the min is 3, then the middle is 8/2 = 4. With your way, the middle would be 1.

2
  • Thanks very much! That helped. Oct 12 '17 at 14:01
  • @JamieGreen You're welcome. Can you please accept my answer so this will be removed from the "unsolved" category. Thanks!
    – curiouskiwi
    Oct 12 '17 at 21:53

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .