I am trying to implement bubble sort, but in the end, the list isnt sorted at all.

It looks like this, and I cant find the error:

    void sort(int values[], int n)
    //Printing unsorted list
    for(int l = 0; l < n; l++)
        printf("Unsorted %i \n", values[l]);

    // Implement Bubble sort
    for(int j = 0; j <= n-1; j++)
        int swaps = 0;
        int k = 0;
        for(int i = 0; i < n - k; i++)
            if(values[i] > values[i+1])
                swap(&values[i], &values[i+1]);
                printf("swaps: %i\n", swaps);
                //Printing sorted list
                for(int m = 0; m < n; m++)
                    printf("Sorted %i \n", values[m]);

            if(swaps == 0)


The unsorted list is:

Unsorted 34 
Unsorted 17 
Unsorted 51 
Unsorted 12 
Unsorted 33 
Unsorted 56 
Unsorted 11 
Unsorted 31 
Unsorted 16 
Unsorted 55 

And the sorted list comes out like this:

Sorted 17 
Sorted 34 
Sorted 12 
Sorted 33 
Sorted 51 
Sorted 56 
Sorted 11 
Sorted 31 
Sorted 16 
Sorted 55 

PS: The swap function is working, I tested it already.


There are two problems with the code. Both are truncating the sort prematurely.

First, the inner loop is being wound down too fast by incrementing k within the loop. It should not be decremented within the inner loop. Instead, try using j.

Second, you are testing whether a swap has occurred within the inner loop. If the first two elements are in order, this will trigger a return before the list is sorted. The inner loop must run to completion before making this test. Move the test outside of the inner loop.

Fix these two issues and it should work correctly.

If this answers your question, please mark this question as answered. Let's keep up on forum housekeeping. ;-)

You must log in to answer this question.

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