I'm going insane! Pset3 binary search. My code seems to be correct but I keep getting errors when trying to make helpers. Find works with generate when I search for a number that exists but hangs when I search for a number not in the generated list. The commented out "return false" creates a "linker command failed to exit code 1" error, but without it I get "control may reach end of non-void function." After researching, I understand the non-void function indicates that somehow my code has the potential to get stuck in a loop in a situation that an if doesn't return. The linker command I'm lost about. I know what the appliance is telling me the problem is, but unsure how to fix it. Any explanation would be great. Below is my code.
bool search(int value, int values[], int n)
{
// implement a searching algorithm
// DETERMINE N (SIZE) IS POSITIVE
int location;
int start = 0;
int end = n;
int range = n;
if (n <= 0)
{
return false;
}
// IF N IS POSITIVE THEN
else
{
// LOOP WHILE SIZE OF STACK IS GREATER THAN 0
while (range > 0)
{
// MAKE LOCATION VALUE EQUAL TO THE MIDPOINT OF START/END
location = start + (range / 2);
// IF THE VALUE IS THAT MIDPOINT
if (value == values[location])
{
return true;
}
else
{
// IF VALUE IS LESS THAN LOCATION VALUE, SHRINK ENDPOINT
if (value < values[location])
{
end = location;
}
// IF VALUE IS GREATER THAN LOCATION VALUE, SHRINK START
else
{
start = location;
}
// ESTABLISH NEW RANGE
range = end - start;
}
if (range == 0)
{
return false;
}
}
}
//return false;
}
linker command failed to exit code 1
error you get is probably because you forget to include a library you use in your main program that calls search.