For some reason my implementation of binary search for Pset3 fails to work correctly whenever the last number added to the "haystack" is 42. During use of GDB, I found that this is due to the part of my code after the while loop where is sets the currentvalue variable according to the state of the variable i. Despite i pointing to the correct location in the array, the currentvalue update fails to return 42 and instead gives me 41 when searching in the numbers "40, 41, 42".
The distinctly strange thing is that once every 10 or so run throughs of the code in GDB, it actually WOULD update to 42 and pass correctly, which even further confused me. Your help is much appreciated.
// Binary search
int i = n - 1;
int min = 0;
int max = n - 1;
int currentval = 0;
while ((max - min) > 0)
{
// Check middle of array
i = (min + max) / 2;
currentval = values[i];
// Check if middle of array is value
if (currentval == value)
{
return true;
}
// Is value larger than i? check 2nd half, else check first
if (value > values[i])
{
min = i + 1;
}
else
{
max = i - 1;
}
}
// Check if middle of array is value
currentval = values[i];
if (currentval == value)
{
return true;
}
return false;
}