I have a file containing sorted numbers 1 to 20, on which I run the search. It finds 0 when it's not in the values. Why is this?
When int end = n;
is used, 20 isn't found. However, when I use int end = n + 1;
, 20 is found. Why is this?
bool search(int value, int values[], int n)
{
// TODO: implement a searching algorithm
int start = 0;
int end = n + 1;
int m;
int i = 0;
while ( n > i)
{
// find middle
m = start + end;
m /= 2;
if (m == value)
{
return true;
}
// shift middle to right by 1
else if (value > m)
{
start = m++;
}
// shift middle to left by 1
else if (value < m)
{
end = m--;
}
i++;
}
return false;
}