bool search(int value, int values[], int n)
{
int found = 0;
int notfound = 0;
int minindex = 0;
int maxindex = n;
int midindex = 0;
do
{
midindex = (minindex + maxindex) / 2;
if (minindex > maxindex)
{
notfound = 1;
return false;
}
else if (value > values[midindex])
{
minindex = midindex + 1;
}
else if (value < values[midindex])
{
maxindex = midindex - 1;
}
else
{
found = 1;
return true;
}
} while (found == 0 && notfound == 0);
}
Q1) Why does the above code not compile but causes "helpers.c:51:1: error: control may reach end of non-void function" error? I found online that the error is caused when a value may not be returned as a result of the function running. However, I don't ever see the possibility of this code not returning true or false booleans.
bool search(int value, int values[], int n)
{
int found = 0;
int notfound = 0;
int minindex = 0;
int maxindex = n;
int midindex = 0;
do
{
midindex = (minindex + maxindex) / 2;
if (value < values[minindex] || value > values[maxindex])
{
notfound = 1;
return false;
}
else if (value > values[midindex])
{
minindex = midindex + 1;
}
else if (value < values[midindex])
{
maxindex = midindex - 1;
}
else
{
found = 1;
return true;
}
} while (found == 0 && notfound == 0);
if (found == 1)
return true;
else
return false;
}
Q2) Why does the above code always return false? Instead of checking for the indexes, I am checking for if the key value I am looking for is outside the bounds of minindex and maxindex. However, the code always returns false. For example, if the array has 1 and 10 as integers, and the value I'm looking for is 10 it returns false. Wouldn't the thought process of the code be: initial midindex is 0, inital minindex is 0, initial maxindex is 1, so the value 10 > 0, increase the minindex to 1. therefore both maxindex and minindex is 1, so the next iteration there midindex is 1. 10 is not greater than values[maxindex] or smaller than values[minindex], is not greater than values[midindex], is not smaller than values[midindex], therefore return true?
I've seen some solutions as taking maxindex=n-1 starting.
However, this search function is inputting "size" from the find.c function, which should be the correct index numbers as it is counting from 0.