The code below fails to pass the last input of check50, namely {39,40,41,43} and I know it isn't a bug in the code itself, after hours of tinkering and rewriting it I'm pretty sure this code works properly. So I manually did the math on that specific input and I came to the conclusion that this method of binary search is faulty. I'm asking can it be done in some different way because my googling hasn't showed me anything much different than this.

bool search(int value, int values[], int n)
    int a = values[0];
    int z = values[n-1];
    int mid;
    while (a<=z)
        mid = (a+z)/2;
        if (value>mid)
            a = mid + 1;
        else if (value==mid)
            return true;
        else if (value<mid)
            z = mid - 1;
    return false;

I'm not sure how much help I'm allowed to provide. Please let me know if I went too far or if I'm allowed to provide more specific help.

I think "a", "z" and "mid" should be positions on the array as opposed to the content of the array at those positions. Then the comparison inside the if statements should be between the content of the array at those positions.

Take another look at the short on binary search, especially at the algorithm they describe in it.

You must log in to answer this question.

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