Simple Bubble Sort Program using functions 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 Program using functions in C

/* Simple Bubble Sort Program Using Functions 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;

    printf("Simple Bubble Sort Example - Array and Functions\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]);
    }

    bubble_sort(arr_sort);
    getch();
}

void bubble_sort(int fn_arr[]) {
    int i, j, a, t;

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

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

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

Sample Output:

Simple Bubble Sort Example - Array and Functions

Enter 5 Elements for Sorting
677
45
32
1
17

Your Data   :   677     45      32      1       17
Iteration 1 :   45      32      1       17      677
Iteration 2 :   32      1       17      45      677
Iteration 3 :   1       17      32      45      677
Iteration 4 :   1       17      32      45      677

Sorted Data :   1       17      32      45      677