0

My search code:

int low = 0;
int high = n-1;
int mid = (high + low) / 2;

// while there are searchable elements
while (low <= high)
{
    {
    // if middle of values is equal to value, return true
    if (values[mid] == value)
    return true;
    }
    {
    // if middle of values is greater than value, look to the left
    if (values[mid] > value)
    high = mid-1;
    }
    {
    // if middle of values is less than value, look to the right
    if (values[mid] < value)
    low = mid+1;
    }
}
return false;

My sort code:

void sort(int values[], int n)
{
// TODO: implement an O(n^2) sorting algorithm

for(int i = 0; i < n; i++)
    {
    for (int j = i+1; j < n; j++)
        {
        if (values[i] > values[j])
        swap (&values[i], &values[j]);
        }

    }

return;

Check50 returns:

:) helpers.c exists

:) helpers.c compiles

:( finds 42 in {42,43,44}

\ expected an exit code of 0, not 1

:) finds 42 in {41,42,43}

:( finds 42 in {40,41,42}

\ expected an exit code of 0, not 1

:) finds 42 in {41,42,43,44}

:( finds 42 in {40,41,42,43}

\ killed by server

:( finds 42 in {39,40,41,42}

\ killed by server

:) doesn't find 42 in {39,40,41}

:( doesn't find 42 in {39,40,41,43}

\ killed by server

:( finds 42 in {42,40,39,41}

\ killed by server

Where should I start trying to resolve these issues? I don't understand the issues, I have gone through search and sort codes and the logic seems okay.

Many thanks for any insight

0

Your mid always stays the same, so you either hit it at first try, or run into infinite loop.

The calculation of mid should be done at the start of your loop, not before the loop, so it's always the middle of the current search interval.

Also, your use of braces around the ifs is somewhat confusing. Use either

    // if middle of values is equal to value, return true
    if (values[mid] == value)
        return true;

or

    // if middle of values is equal to value, return true
    if (values[mid] == value)
    {
        return true;
    }

You must log in to answer this question.

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