Search code examples
cbubble-sort

Bubble sort in C: Function not changing array data


Code:

#include <stdio.h>

void testSort(int values[], int n);

int main(void)
{
    int hs[] = {5,3,2,1,4};
    printf("Unsorted: %i %i %i %i %i\n", hs[0], hs[1], hs[2], hs[3], hs[4]);
    testSort(hs, 5);

    printf("Sorted: %i %i %i %i %i\n", hs[0], hs[1], hs[2], hs[3], hs[4]);
}

void testSort(int values[], int n)
{
    for (int i = 0; i < n-1; i++)
    {
        int hold;
        int current = values[i];
        int next = values[i + 1];

        if (current > next)
        { 
            hold = current;
            current = next;
            next = hold;
        }
    }
    return;
}

I'm trying to do bubble sort and right now it goes through the array once, but my question is: Why isn't my hs[] updating after calling function? The second printf shows that it remained the same.

EDIT: As mentioned, turns out I was changing data but of the copies. For some reason I when I created the variables current/next I felt as if they were representing values[i]/values[i+1] but in reality I was just creating new variable and passing the value of values[0] which is 5 and assigning it to current. Obviously leaving values[] unchanged. Thanks everyone


Solution

  • The problem is that you're only modifying the function's local variables, not the array's elements.

    It's the same principle as why this program will print 1 and not 2:

    int main()
    {
        int array[] = {1};
        int x = array[0];
        x = 2;
        printf("array[0] = %d\n", array[0]);
        return 0;
    }
    

    You need to assign values to the array's elements:

    void testSort(int values[], int n)
    {
        for (int i = 0; i < n-1; i++)
        {
            if (values[i] > values[i+1])
            { 
                int hold = values[i];
                values[i] = values[i+1];
                values[i+1] = hold;
            }
        }
    }
    

    Once you've fixed this, you will notice that this function only works for some inputs.
    Solving that bug is left as an exercise.