I want to implement binary search for an array of integers. I made sure that array sorted incrementally. But my function is not tracking all the cases and some of the checks fail. What am I missing here?
Value stands for integer I'm trying to find.
bool search(int value, int array[], int n)
{
int left = 0;
int right = n - 1;
int middle = (left + right) / 2;
while (right >= left)
{
if (array[middle] == value)
return true;
else if (array[middle] < value)
right = middle;
else if (array[middle] > value)
left = middle + 1;
middle = (left + right) / 2;
}
return false;
}
My guess is that some left or right border cases are not predicted. I also not strong about while condition.
middlecomputation, which is easily missed in human-scaled test cases. Wikipedia has notes on this. The recommended expression ismiddle = left + (right - left) / 2;.