0
bool search(int value, int values[], int n)
{
// TODO: implement a searching algorithm
if (value < 0)
    return false;
int s = 0;
int e = n - 1;
int m = ((s + e) / 2);

while (s <= e)
    {
        if (value == values [m])
            return true;

        else if (value > values [m])
            {
                s = m + 1;
                m = ((s + e) / 2);
            }
        else
            {
                e = m - 1;
                m = ((s + e) / 2);
            }
    }
return false;
}

"...haystack[998] =

haystack[999] =

haystack[1000] =

Didn't find needle in haystack.

~/workspace/pset3/find/ $ echo $? 1..."

The above is what I get after performing ./generate 1000 50 | ./find 127

as per CS50 testing instructions.

Above is my code for the search function where I think the issue is. Anyone had a similar problem?

I also seem to have issues with the sort function according to check50:

void sort(int values[], int n)
{
// TODO: implement a sorting algorithm
int m, c;
for (int i = 0; i < n - 1; i++)
    {
        m = i;
        for (int j = i + 1; j < n; j++)
            {
                if (values [j] < values [m])
                    m = j;
            }
        if (m != i)
        {
            c = values [m];
            values [i] = values [m];
            values [m] = c;
        }
    }

return;
}
0

search looks correct. Placement of m = ((s + e) / 2) might be better, if placed as the first instruction within the while loop, you need it only once, not three times. I don't see the equivalent of if (value < 0) return false; in the rules, but since the input data generated by generate is all between 0 and 65535, it wouldn't matter. Maybe you confused it with

Your implementation must return false immediately if n is non-positive.

which is already handled by your while loop (it just won't run even once). I'd remove the if (value < 0) part.

But the real problem lies in sort, in your swap code. Instead of c = values [m]; use c = values[i];.

| improve this answer | |

You must log in to answer this question.

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