I've been stuck with this particular problem for a while and can't think of what goes wrong. So any help will be much appreciated :) Binary search seems to work with all cases except when the searched element is the first one (for instance, if we look for 28 and input an array of 3 elements [28, 29, 30]). When we are through the first loop in value < values[middle] condition, we call the function recursively with an array size of one and should end up in condition value == values[middle], but it doesn't really happen.
bool search(int value, int values[], int n)
{
if (n < 2)
{
if (value == values[0])
{
return true;
}
else
{
return false;
}
}
int middle = n/2;
int NewArray[middle];
if (value == values[middle])
{
return true;
}
else if (value > values[middle])
{
int NewSize = n - middle - 1;
for (int i = 0, j = middle+1; i < NewSize; i++, j++)
{
NewArray[i] = values[j];
}
return search(value, NewArray, NewSize);
}
else if (value < values[middle])
{
int NewSize = n - middle;
for (int i = 0, j = 0; i < middle; i++, j++)
{
NewArray[i] = values[j];
}
return search(value, NewArray, NewSize);
}
else
{
return false;
}
}