C Language Practice: Sorting - Bubble Sort

Revision as of 10:18, 25 March 2022 by Eric (talk | contribs) (Created page with "== Bubble sort == '''What is bubble sort?''' Bubble sort is another way of sorting. Its code is easier than selection sort, and its speed is also faster. What we want to do in bubble sort is that we compare the first two elements, and see if we need to swap it. Then we compare the second and third, then the third and fourth, and so on and so on until we compared the whole list. If we didn't need to swap at all, then the list is sorted and we can return it. If not, go...")
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)

Bubble sort

What is bubble sort?

Bubble sort is another way of sorting. Its code is easier than selection sort, and its speed is also faster. What we want to do in bubble sort is that we compare the first two elements, and see if we need to swap it. Then we compare the second and third, then the third and fourth, and so on and so on until we compared the whole list. If we didn't need to swap at all, then the list is sorted and we can return it. If not, go to the second round and repeat, until the list is sorted and we can return it.


Train of thought in coding

Using the explanation above, we have a pretty clear direction in our code.

  • Step 1: We need to define a variable that stores the number of swaps. Because then, we'll be able to see if we need to swap or we don't need to swap at all.
  • Step 2: We'll build a while loop that keeps us running until we don't need to swap at all.
  • Step 3: Let  (the variable that stores the number of swaps) be zero at first, then build a for loop and compare the elements in the list.
  • Step 4: Well, there's no step 4. Return it~


#include <stdio.h>

int bubblesort(int array[], int total)
{
    int snum = 1, j, f, temp;

    while (snum != 0)
    {
        snum = 0;
        for (int i = 0; i < total - 1; i++)
        {
            if (array[i] > array[i + 1])
            {
                snum++;
                temp = array[i];
                array[i] = array[i + 1];
                array[i + 1] = temp;
            }
        }
    }

    return array;
}

int main(void)
{
    int total;
    printf("how many numbers do you want to enter?\n");
    scanf("%d", &total);
    int array[total];
    printf("enter your number list here.\n");
    for (int i = 0; i < total; i++)
    {
        scanf("%d", &array[i]);
    }

    bubblesort(array, total);

    printf("the sorted list is:\n");
    for (int f = 0; f < total; f++)
    {
        printf("%d ", array[f]);
    }
    printf("\n");

    return 0;
}