Bubble sort sweeps through the array comparing neighbors; whenever a pair is out of order, it swaps them. After the first sweep, the largest element has bubbled to the last position, it's guaranteed, because wherever the max starts, it wins every neighbor comparison it meets. Second sweep puts the second-largest second-from-last, and so on. The sorted region grows from the right.
It's the first sorting algorithm you should learn because every idea in sorting analysis appears: invariants (the tail is final after pass k), best/average/worst cases, and the difference between comparisons (always ~n²/2) and swaps (0 to n²/2). It's also the last algorithm you should ship: its O(n²) comparisons make it 100× slower than merge sort at n = 10,000, teachers use it because it's transparent, not because it's good.
One full trace: [5, 1, 4, 2]
- 1
Pass 1
5>1 swap → [1,5,4,2]; 5>4 swap → [1,4,5,2]; 5>2 swap → [1,4,2,5]. Largest (5) is now final at the end. 3 comparisons, 3 swaps.
- 2
Pass 2
1≤4 keep; 4>2 swap → [1,2,4,5]. 4 is final. 2 comparisons, 1 swap.
- 3
Pass 3
1≤2 keep. 1 comparison, 0 swaps, no swaps means fully sorted, stop early.
- 4
Total
6 comparisons, 4 swaps. Worst case would be 6 comparisons too (3+2+1), quadratic regardless of data.
Implementation with early exit
// Pure: returns a new sorted array. Stable.
function bubbleSort(input) {
const arr = [...input];
const n = arr.length;
for (let pass = 0; pass < n - 1; pass++) {
let swapped = false;
for (let i = 0; i < n - 1 - pass; i++) { // tail [n-1-pass..] already final
if (arr[i] > arr[i + 1]) {
[arr[i], arr[i + 1]] = [arr[i + 1], arr[i]];
swapped = true;
}
}
if (!swapped) break; // early exit: a clean pass proves sortedness
}
return arr;
}| Operation / case | Cost | Notes |
|---|---|---|
| Best case (sorted input) | O(n) | early exit after one clean pass |
| Average & worst case | O(n²) | ~n²/2 comparisons |
| Swaps (worst) | O(n²) | reversed input |
| Space | O(1) | in-place, swaps neighbors |
| Stable? | Yes | equal elements never jump over each other |