Bubble sort in C: solved exercise step by step

  2 minutes

If you searched for bubble sort in C solved exercise, this page explains the algorithm and its common optimization.

Sort an integer array ascending using bubble sort and stop early when no swaps happen.

#include <stdio.h>

void bubble_sort(int a[], int n) {
    for (int i = 0; i < n - 1; i++) {
        int swapped = 0;

        for (int j = 0; j < n - 1 - i; j++) {
            if (a[j] > a[j + 1]) {
                int tmp = a[j];
                a[j] = a[j + 1];
                a[j + 1] = tmp;
                swapped = 1;
            }
        }

        if (!swapped) break;
    }
}

int main(void) {
    int a[] = {9, 3, 7, 1, 4};
    int n = sizeof(a) / sizeof(a[0]);

    bubble_sort(a, n);
    for (int i = 0; i < n; i++) printf("%d ", a[i]);
    printf("\n");
    return 0;
}
1 3 4 7 9
  • Worst case: O(n^2)
  • Best case (optimized): O(n)
  • Not shrinking inner range with - i.
  • Forgetting to reset swap flag.
  • Confusing stability with speed.

Not the fastest algorithm, but great for teaching, sanity checks, and tiny datasets.

If you want a complete path with progressive difficulty:

Yes. It targets patterns that commonly appear in practice assignments, technical interviews, and C programming exams.

In Programming in C in 100 Solved Exercises and C Exercises. Kindle Unlimited: View on Amazon.

Start with small inputs, run edge cases (empty, one item, max capacity), then rewrite the solution from scratch without copying.