Sorting

Bubble sort · source
1function bubbleSort(a: number[]) {
2 const n = a.length;
3 for (let i = 0; i < n - 1; i++) {
4 let swapped = false;
5 for (let j = 0; j < n - 1 - i; j++) {
6 if (a[j] > a[j + 1]) {
7 [a[j], a[j + 1]] = [a[j + 1], a[j]];
8 swapped = true;
9 }
10 }
11 if (!swapped) break;
12 }
13 return a;
14}
Bubble sort · liveAdjacent swaps push the largest value right on every pass.

Start with 12 elements. Each pass bubbles the largest remaining value to the right.

1 / 121

How bubble sort works

Each pass walks the array comparing neighbours and swapping any pair that is out of order. After pass one, the largest element has bubbled to the last slot; after pass two, the second largest is in place — so every pass shrinks the unsorted region by one from the right.

The swapped flag is the detail interviewers probe: if a full pass makes zero swaps, the array is already sorted and the loop exits early. That is what makes the best case O(n) instead of O(n²) — worth saying out loud before you are asked.

In practice bubble sort is a teaching tool, not a production sort. Its value is that the invariant is visible: watch the green region grow from the right, one settled element per pass.

space play / pause · step

Complexity

bestO(n)
averageO(n²)
worstO(n²)
spaceO(1)
stableyes