Kodewick
Start learning →

Bubble sort in C, visualized step by step

Walk through the list comparing neighbours, and swap them when the left one is bigger. After each pass the largest number has "bubbled" to the end; a pass with no swaps means the list is sorted, so it stops early.

bubble_sort.c
#include <stdio.h>

int main(void) {
    int a[] = {5, 1, 4, 2, 8};
    int n = 5;
    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 t = a[j];
                a[j] = a[j + 1];
                a[j + 1] = t;
                swapped = 1;
            }
        }
        if (!swapped) break;
    }
    for (int i = 0; i < n; i++) printf("%d ", a[i]);
    printf("\n");
    return 0;
}
Press ▶ to play, or ‹ › to stepEdit this code in the online compiler ↗

How Bubble sort works

  1. Go from left to right, comparing two neighbours at a time.
  2. If the left one is bigger, swap them: after one pass the largest is at the end.
  3. Each pass compares one fewer: the end is already sorted.
  4. A whole pass without a swap ends it early (the swapped flag).

What to watch

j moving rightThe tallest bar travels with j all the way to the right end.
swappedIt stays false on the last pass, and the loop stops there.

FAQ

What is the time complexity of bubble sort?

O(n²) in the worst and average case: two nested loops, n(n − 1)/2 comparisons. With the early exit, an already sorted list takes one pass: O(n).

Is bubble sort stable?

Yes. It only swaps when the left value is strictly greater, so equal values never change order.

Is bubble sort used in real code?

Hardly ever: it is too slow for large inputs. Use sorted() / list.sort() in Python or qsort() in C. It is worth learning because it shows the two basic moves of sorting, compare and swap.

More algorithms

All 10 algorithm visualizations →