I am having some serious issues figuring out what is wrong with my code. I have run this through on paper with the simplest of numbers and cant seem to understand why it fails. I could use some direction in what I have missed.
here is the relevant code...
bool search(int value, int values[], int n)
{
int min = 0, max = (n - 1), mid = ((max + min) / 2);
while (min <= max)
{
if (values[mid] == value)
return true;
else if (values[mid] > value)
{
max = (mid - 1);
mid = ((max + min) / 2);
}
else if (values[mid] < value)
{
min = (mid + 1);
mid = ((max + min) / 2);
}
else
{
return false;
}
}
return false;
}
here is the output...
sh-4.3$ ./find 2
haystack[0] = 0
haystack[1] = 1
haystack[2] = 2
haystack[3] =
Didn't find needle in haystack.