function bubbleSort(array: number[]) { for (let end = array.length - 1; end > 0; end--) {let swapped = false;
for (let j = 0; j < end; j++) { if (array[j] > array[j + 1]) {[array[j], array[j + 1]] = [array[j + 1], array[j]];
swapped = true;
}
}
if (!swapped) break;
}
}
Start: 24 values in random order. Each pass bubbles the largest unsorted value to the end.
Understanding Bubble sort
The idea
Bubble sort walks the array comparing each pair of neighbours and swapping them when they are out of order. After one full pass the largest value has bubbled to the end, so the next pass can stop one position earlier. The sorted suffix grows by one on every pass.
The early exit is the one optimisation worth having: if a pass makes no swap, the array is already sorted and the loop ends. On nearly sorted input that turns n² work into a single pass; on random input it changes nothing.
The four stages
Complexity
Versus its siblings
Pseudocode
BUBBLESORT(array)
for end ← n − 1 down to 1
swapped ← false
for j ← 0 to end − 1
if array[j] > array[j + 1]: swap array[j], array[j + 1]; swapped ← true
if not swapped: return
When to use
Pitfalls
History
Exchange sorts were described as early as 1956 by Edward Friend, and the name bubble sort was popularised by Kenneth Iverson in 1962. Donald Knuth wrote in 1973 that it "seems to have nothing to recommend it, except a catchy name", and it has been the first sort taught in most courses ever since.