0
0
CProgramBeginner · 2 min read

C Program for Bubble Sort with Example and Explanation

A C program for bubble sort repeatedly compares adjacent elements and swaps them if they are in the wrong order using nested loops, like for (int i = 0; i < n-1; i++) { for (int j = 0; j < n-i-1; j++) { if (arr[j] > arr[j+1]) { int temp = arr[j]; arr[j] = arr[j+1]; arr[j+1] = temp; }}}.
📋

Examples

Input5 3 8 4 2
OutputSorted array: 2 3 4 5 8
Input1 2 3 4 5
OutputSorted array: 1 2 3 4 5
Input9 7 5 3 1
OutputSorted array: 1 3 5 7 9
🧠

How to Think About It

To sort an array using bubble sort, think of repeatedly passing through the list, comparing each pair of neighbors, and swapping them if they are out of order. This way, the largest unsorted value 'bubbles' to the end each pass. Repeat until no swaps are needed.
📐

Algorithm

1
Get the array and its size as input.
2
Repeat for each element in the array except the last:
3
Compare each pair of adjacent elements.
4
If the left element is greater than the right, swap them.
5
After each pass, the largest unsorted element moves to its correct position.
6
Stop when the array is fully sorted.
💻

Code

c
#include <stdio.h>

void bubbleSort(int arr[], int n) {
    for (int i = 0; i < n - 1; i++) {
        for (int j = 0; j < n - i - 1; j++) {
            if (arr[j] > arr[j + 1]) {
                int temp = arr[j];
                arr[j] = arr[j + 1];
                arr[j + 1] = temp;
            }
        }
    }
}

int main() {
    int arr[] = {5, 3, 8, 4, 2};
    int n = sizeof(arr) / sizeof(arr[0]);
    bubbleSort(arr, n);
    printf("Sorted array: ");
    for (int i = 0; i < n; i++) {
        printf("%d ", arr[i]);
    }
    return 0;
}
Output
Sorted array: 2 3 4 5 8
🔍

Dry Run

Let's trace the array {5, 3, 8, 4, 2} through the bubble sort code.

1

First pass comparisons and swaps

Compare 5 and 3, swap -> {3, 5, 8, 4, 2}; compare 5 and 8, no swap; compare 8 and 4, swap -> {3, 5, 4, 8, 2}; compare 8 and 2, swap -> {3, 5, 4, 2, 8}

2

Second pass comparisons and swaps

Compare 3 and 5, no swap; compare 5 and 4, swap -> {3, 4, 5, 2, 8}; compare 5 and 2, swap -> {3, 4, 2, 5, 8}

3

Third pass comparisons and swaps

Compare 3 and 4, no swap; compare 4 and 2, swap -> {3, 2, 4, 5, 8}

4

Fourth pass comparisons and swaps

Compare 3 and 2, swap -> {2, 3, 4, 5, 8}

PassArray State
13 5 4 2 8
23 4 2 5 8
33 2 4 5 8
42 3 4 5 8
💡

Why This Works

Step 1: Nested loops for passes and comparisons

The outer loop controls how many passes we make, and the inner loop compares adjacent elements to swap if needed.

Step 2: Swapping elements

When the left element is bigger than the right, swapping moves the bigger element towards the end.

Step 3: Reducing comparisons each pass

Each pass places the largest unsorted element at the end, so the inner loop shortens by one each time.

🔄

Alternative Approaches

Optimized Bubble Sort with Early Exit
c
#include <stdio.h>

void bubbleSortOptimized(int arr[], int n) {
    int swapped;
    for (int i = 0; i < n - 1; i++) {
        swapped = 0;
        for (int j = 0; j < n - i - 1; j++) {
            if (arr[j] > arr[j + 1]) {
                int temp = arr[j];
                arr[j] = arr[j + 1];
                arr[j + 1] = temp;
                swapped = 1;
            }
        }
        if (!swapped) break;
    }
}

int main() {
    int arr[] = {5, 3, 8, 4, 2};
    int n = sizeof(arr) / sizeof(arr[0]);
    bubbleSortOptimized(arr, n);
    printf("Sorted array: ");
    for (int i = 0; i < n; i++) {
        printf("%d ", arr[i]);
    }
    return 0;
}
Stops early if no swaps happen in a pass, improving performance on nearly sorted arrays.
Selection Sort
c
#include <stdio.h>

void selectionSort(int arr[], int n) {
    for (int i = 0; i < n - 1; i++) {
        int min_idx = i;
        for (int j = i + 1; j < n; j++) {
            if (arr[j] < arr[min_idx]) {
                min_idx = j;
            }
        }
        int temp = arr[min_idx];
        arr[min_idx] = arr[i];
        arr[i] = temp;
    }
}

int main() {
    int arr[] = {5, 3, 8, 4, 2};
    int n = sizeof(arr) / sizeof(arr[0]);
    selectionSort(arr, n);
    printf("Sorted array: ");
    for (int i = 0; i < n; i++) {
        printf("%d ", arr[i]);
    }
    return 0;
}
Selects the smallest element each pass and swaps it to the front; fewer swaps but still O(n²) time.

Complexity: O(n²) time, O(1) space

Time Complexity

Bubble sort uses two nested loops over the array, so it takes about n×n = n² steps in the worst and average cases.

Space Complexity

It sorts the array in place, so it only needs a few extra variables, making space complexity constant O(1).

Which Approach is Fastest?

Optimized bubble sort can be faster on nearly sorted data by stopping early, but selection sort reduces swaps, which can be better in some cases.

ApproachTimeSpaceBest For
Bubble SortO(n²)O(1)Simple, small arrays
Optimized Bubble SortO(n) best, O(n²) worstO(1)Nearly sorted arrays
Selection SortO(n²)O(1)When swaps are costly
💡
Use an early exit flag to stop bubble sort if the array is already sorted to save time.
⚠️
Beginners often forget to reduce the inner loop range each pass, causing unnecessary comparisons.