Bubble sort compares adjacent pairs and swaps them if out of order. After each pass the largest remaining element has "bubbled" to its final position at the end. If a pass makes no swaps the array is sorted and the loop can stop early. It is O(n^2) average and worst case, O(n) best case with the early exit, stable and in place.
Remember
for (i = 0; i < n - 1; i++) {
swapped = 0;
for (j = 0; j < n - 1 - i; j++)
if (a[j] > a[j + 1]) { swap(a[j], a[j + 1]); swapped = 1; }
if (!swapped) break;
}
Reference
Cheat Sheet
Keep these facts handy while you work with Bubble Sort in C.
Topic
Detail
Best
O(n) with early exit
Average / worst
O(n^2)
Space
O(1)
Stable
Yes
Code
C Examples
Compile each example with gcc file.c -std=c11 -Wall -o out. Next: Selection Sort.
Example 1 — Trace each pass
Sort 64, 25, 12, 22, 11.
C
#include <stdio.h>
int main(void) {
int a[] = {64, 25, 12, 22, 11};
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;
}
}
printf("pass %d:", i + 1);
for (int k = 0; k < n; k++) printf(" %d", a[k]);
printf("\n");
if (!swapped) break;
}
return 0;
}