Sage-Code Laboratory
index<--

Bubble Sort (c)

What a ride. Now let’s see what we have learned in our short tutorial. Here is an example of algorithm called bubble sort. If you understand this algorithm you have done a good job. 

Algorithm:

#include <stdio.h>
int main()
{
    int n, temp;
    printf("Number of elements to sort:");
    scanf("%d", &n);
    /* create a dynamic allocated array named "array" */
    int *array = calloc(n, sizeof(int));
    /* remember to check if the allocation is successful */
    if (array == NULL) {
        fprintf(stderr, "calloc failed\n");
        return(-1); // fail the program with error code -1
    }
    printf("Enter %d integers...\n", n);
    /* read elements of array */
    for (int i = 0; i < n; i++) {
        printf("array[%d] = ",i);
        scanf("%d", &array[i]);
    }
    /* sort elements of array */
    int swap, i = 0;
    /* scan all elements until there is no swap*/
    do {
        swap = 0; //assume the swap failed
        for (i = 0 ; i < n - 1; i++) {
            if (array[i] > array[i+1]) {
                /* execute swap */
                temp = array[i];
                array[i] = array[i+1];
                array[i+1] = temp;
                swap = 1; //set swap flag
            }
        }
    } while (swap);
    /* output the result */
    printf("Sorted array:\n");
    /* array traversal */
    for (int i = 0; i < n; i++)
        printf("%d, ", array[i]);
    return 0;
}

Note: This program is interactive. First you enter a number of elements to be sorted, then the program is sorting the elements and display them in sorted order. Careful read the example and try to remember what you have learned.

Homework:  Open and run this program on-line on repl.it website: bubble sort

Thanks for reading!

If you have finished this tutorial, I'm very impressed! Next you can go back to the index page and investigate our external references. You will find links to valuable resources to continue your C language study.


Back to: C Tutorial