0

I decided to do pset 3 from 2017 as extra practice, but ran into an issue with bubble sort. More specifically, when I run check50 on it I get:

:( sorts {5,4,3,2,1} expected "1", not "\n5\n5\n5\n5\n5..."

and one other comparable error. The other tests check out. I'm defining swaps ahead of the loop too because it won't let me compile otherwise.

// Bubble sort
void sort(int values[], int n)
{
    int swaps = 0;
    do
    {
        // Until penultimate element
        int swaps = 0;
        for (int i = 1; i < n; i++)
        {
            if (values[i] > values[i + 1])
            {
                int tmp = values[i];
                values[i + 1] = values[i];
                values[i] = tmp;
                swaps++;
            }
        }
        n--;
    }
    while (swaps > 0);
    return;
}

1 Answer 1

0

In your swap code, there's a mistake (you have three times i but only i+1 only once, should be two each, once on the left and once on the right side).

Your second int swaps = 0; should be just swaps = 0;, otherwise you'd create another variable of the same name. So while you increment inner swaps, the loop tests outer swaps, which stays at zero. Within the loop, the second/inner variable of the same name prevents the outer one from being accessed, the technical term is "shadowing".

Also, your loop is running in the wrong range. If you're using i and i+1, I'd use for (int i = 0; i < n - 1; i++). With your numbers, the first pair is never swapped, and in the last iteration you'd compare to values[n], which does not exist.

You must log in to answer this question.