Bubble Sort using C

Introduction

Bubble sort is one of the most popular sorting methods. It can be treated as a selection sort because it is based on successively selecting the smallest element, second smallest element and so on.

In order to find the successive smallest elements this process relies heavily on the exchange of the adjacent elements and swaps them if they are in the wrong order.

Time Complexity

Bubble sort has worst-case and average complexity both О(n2), where n is the number of items being sorted.

Pictorial Representation

Pictorial representation of bubble sort is given below (image from Wikipedia):

Bubble Sort using C

The complete source code using C program is given below:

/* 
 * File:   BubbleSort.c
 * Author: https://roytuts.com
 */

#include <stdio.h>
#include <stdlib.h>

void bubbleSort(int a[], int n) {
    int i, j, k;
    int temp;
    for (i = 0; i < n; i++) {
        j = n - 1;
        k = 0;
        while (j > i) {
            if (a[j] < a[j - 1]) {
                temp = a[j];
                a[j] = a[j - 1];
                a[j - 1] = temp;
                k = 1;
            }
            j--;
        }
        if (k == 0) {
            break;
        }
    }
    printf("\n");
    printf("\nThe sorted array elements are given below\n");
    for (i = 0; i < n; i++) {
        printf("a[%d]=%d ", i, a[i]);
    }
}

int main() {
    int i, n = 6;
    int a[] = {15, 8, 17, 12, 38, 19};
    printf("\n:: Bubble Sort ::\n");
    printf("\nInput array elements\n");
    for (i = 0; i < n; i++) {
        printf("a[%d]=%d ", i, a[i]);
    }
    bubbleSort(a, n);
}

Testing the Program

By executing the above program we will get below output:

:: Bubble Sort ::

Input array elements
a[0]=15 a[1]=8 a[2]=17 a[3]=12 a[4]=38 a[5]=19 

The sorted array elements are given below
a[0]=8 a[1]=12 a[2]=15 a[3]=17 a[4]=19 a[5]=38

Source Code

Download

Leave a Reply

Your email address will not be published. Required fields are marked *