Simple Bubble Sort Program in C


Definition

Bubble sort, sometimes referred to as sinking sort, is a simple sorting algorithm that repeatedly steps through the list to be sorted, compares each pair of adjacent items and swaps them if they are in the wrong order. The pass through the list is repeated until no swaps are needed, which indicates that the list is sorted. It can be practical if the input is usually in sort order but may occasionally have some out-of-order elements nearly in position.

Simple Bubble Sort C Program

/* Simple Bubble Sort Program Using Array in C*/
/* Data Structure Programs,C Array Examples */

#include<stdio.h>
#include<conio.h>

#define MAX_SIZE 5

void bubble_sort(int[]);

int main() {
    int arr_sort[MAX_SIZE], i, j, a, t;

    printf("Simple Bubble Sort Example - Array\n");
    printf("\nEnter %d Elements for Sorting\n", MAX_SIZE);
    for (i = 0; i < MAX_SIZE; i++)
        scanf("%d", &arr_sort[i]);

    printf("\nYour Data   :");
    for (i = 0; i < MAX_SIZE; i++) {
        printf("\t%d", arr_sort[i]);
    }

    for (i = 1; i < MAX_SIZE; i++) {
        for (j = 0; j < MAX_SIZE - 1; j++) {
            if (arr_sort[j] > arr_sort[j + 1]) {
                //Swapping Values 
                t = arr_sort[j];
                arr_sort[j] = arr_sort[j + 1];
                arr_sort[j + 1] = t;
            }
        }

        printf("\nIteration %d : ", i);
        for (a = 0; a < MAX_SIZE; a++) {
            printf("\t%d", arr_sort[a]);
        }
    }

    printf("\n\nSorted Data :");
    for (i = 0; i < MAX_SIZE; i++) {
        printf("\t%d", arr_sort[i]);
    }
}

Sample Output:

Simple Bubble Sort Example - Array

Enter 5 Elements for Sorting
980
7
45
891
1

Your Data   :   980     7       45      891     1
Iteration 1 :   7       45      891     1       980
Iteration 2 :   7       45      1       891     980
Iteration 3 :   7       1       45      891     980
Iteration 4 :   1       7       45      891     980

Sorted Data :   1       7       45      891     980

------------------
(program exited with code: 0)

Press any key to continue . . .