# Binary search: always false when 2 or 3 numbers entered

My binary search works correctly when you enter 1,4,5,6,7 (etc)... numbers or 'haystacks'. However, when 2 or 3 numbers or 'haystacks' are entered, false is always returned. I have tried everything I can think of and am not having any luck. Thanks in advance.

Here is my problematic code:

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

{ int list = n;

``````int middle = list / 2;
int MIN = 0;
int MAX = n;

while ( MIN < MAX)
{
middle = (MAX + MIN) / 2;

if (values[middle] == value)
return true;
if (value < values[middle])
{
MIN = 0;
MAX = middle - 1;
}

if (value > values[middle])
{
MIN = middle + 1;
MAX = n;
}
}
return false;
``````

}

If we have an array length, the first element is index zero and the last element is the index n -1;

``````int MIN = 0;
int MAX = n - 1;
``````

On the other hand, the while loop to check all the values, if you say while (MIN

``````while ( MIN < MAX)
``````

Another possible problem, think of each iteration of the loop, what about the ends?   they change ?, in the first iteration if (value < values[middle]) MIN doesn't change MIN = 0; It is not necessary, in other iterations of the loop it can happen that value > values[middle], MIN = middle + 1; this is our new lower limit limit, we must and we forget and MIN = 0; I hope it helps to start

• Thank you so much! (changing to n-1 worked) Jul 6 '16 at 22:21