0

Hi this is my binary search code, something is not working, but find what it is? Also, I think the if statements should be changed to (if, else if, else) but the compiler yells at me if I code it like that. Can someone explain why? Tells me to put a ";" after the else. And if I do that the compiler yells again saying "expression result unused".

/**
* Returns true if value is in array of n values, else false.
*/
 bool search(int value, int values[], int n)
{
    // TODO: implement a searching algorithm

int start = 0;
int top = n - 1;
int middle = (start + top) / 2;

while (n > 0)
{
    if(values[middle] == value)
    {
        return true;
    }
    if (values[middle] > value)
    {
        middle = (values[start] + values[middle - 1]) / 2;
        top = values[middle - 1];
    }
    if (values[middle] < value)
    {
        middle = (values[top] + values[middle + 1]) / 2;
        start = values[middle + 1];
    }

}
return false;

}
2
  • can I assume that you have the haystack sorted? – ebobtron Aug 1 '15 at 22:20
  • Yep! If I put a printf() after the sort function in find.c it prints all entered numbers in order. – Alexander Lundskog Aug 2 '15 at 8:45
1

while (n > 0) When would "n" ever not be greater than zero? You'll never leave the loop, never return false.

if else is this:

if(true)
{
    do this if true
}
else
{
    do this if false
}

if else if is this:

if(true)
{
    do this if true
}
else if(true)
{
    do this if second true
}

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .