Bubble sort
Repeatedly swap adjacent values that are out of order until a full pass makes no swaps: simple to understand, O(n²), and almost never the right choice.
Description
Bubble sort walks through the array comparing each pair of neighbors, and swaps them if they're in the wrong order. After the first pass, the largest value has "bubbled up" to the end. Each later pass places the next largest, so the sorted part grows from the right.
With one small improvement, stopping as soon as a pass makes no swaps, bubble sort finishes a sorted array in a single pass: O(n). On anything else it needs about n²/2 comparisons and, on reversed data, as many swaps.
Bubble sort is mostly taught because it's easy to follow. Insertion sort does the same job with fewer swaps and better real-world speed, so it's the simple sort to use if you ever need one.
How it works
One pass: the largest value moves to the end
- index 0: 5
- index 1: 1
- index 2: 4
- index 3: 2
- index 4: 8
Step through: bubble sort
Step 1 of 30Start with 8 values.
Complexity
| Operation | Average | Worst |
|---|---|---|
| Sort (average) | O(n²) | O(n²) |
| Already sorted (with early exit) | O(n) | O(n) |
| Reversed inputEvery comparison is a swap. | O(n²) | O(n²) |
Space: O(1)
Bubble sort is stable and in place, but it makes far more swaps than insertion sort, which matters because swaps are writes.
TypeScript implementation
Bubble sort with the early-exit check, counting passes.
// Bubble sort with an early exit: stop as soon as a pass makes no swaps.
export function bubbleSort(a: number[]): { sorted: number[]; passes: number } {
let passes = 0;
for (let end = a.length - 1; end > 0; end--) {
passes++;
let swapped = false;
for (let i = 0; i < end; i++) {
if (a[i] > a[i + 1]) {
[a[i], a[i + 1]] = [a[i + 1], a[i]];
swapped = true;
}
}
if (!swapped) break; // already sorted
}
return { sorted: a, passes };
}
export function demo(): string[] {
const random = bubbleSort([29, 10, 14, 37, 13, 5, 41, 22]);
const sorted = bubbleSort([1, 2, 3, 4, 5, 6, 7, 8]);
return [
`random → [${random.sorted.join(", ")}] in ${random.passes} passes`,
`already sorted → ${sorted.passes} pass (the early exit makes this O(n))`,
];
}When to use it
Use it when
- Teaching how sorting works, and how to reason about loops and invariants.
- Detecting whether a tiny array is already sorted, in one pass.
Avoid it when
- In almost all real code: use your language's built-in sort.
- If you need a simple sort for small inputs: insertion sort is better.
Pitfalls
- Forgetting the early exit, so sorted input still takes O(n²).
- Scanning the already-sorted tail on every pass instead of shrinking the range.
Alternatives
Insertion sort
Choose it when you want a simple O(n²) sort that's fast on small or nearly sorted data.
Built-in sort (Timsort and others)
Choose it when you're writing real code.