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);
}