0

I am trying to implement a binary search algorithm. However, my while loop isn't working as expected. Having used printf and debug50 with a list of 100 numbers, it seems that the while loop only gets run through once, and always exits true. If I put in printf("DEBUG: %i\n", values[mid]); after the "else if" and "return" in the while loop, it never gets printed.

I'm quite lost. How do I go about fixing this?

bool BinarySearch(int value, int values[], int min, int max)
{
    int low = min, high = max;
    while (low <= high)
    {
        int mid = (low + high)/2;

        if (value == values[mid])
            return true;
        else if (value < values[mid])
            return high = mid - 1;
        else low = mid + 1;
    }
    return false;
}

bool search(int value, int values[], int n)
{
    return BinarySearch(value, values, 0, n - 1);
}
0

You are returning a non-boolean value after the else if which does not make a lot of sense given your algorithm is not recursive. Also, your last else should be a lot clearer despite it being semantically correct -- I think it is, at least.

To give you a perspective on how to fix this: Remember everything inside the while will get executed until there is no more to execute, after which the loop will reset. Therefore you must not return anything but true or false. Again please put the statement after the last else on its own line, it makes intent so much clearer!


If this answers your question please accept the answer by clicking the check mark to remove this question from the unanswered pool, otherwise feel free to leave a comment ;)

You must log in to answer this question.

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