Sorting
Bubble Sort Visualiser
Swap neighbours that are the wrong way round, over and over.
Sort 14 bars by repeatedly swapping neighbours that are the wrong way round.
- Comparisons
- 0
- Writes
- 0
- for scale
- n² = 196
The counter is an exact count for this run; the curve beside it is the shape that count follows as n grows, not a limit on it.
- Being compared
- Being written
- Pivot or smallest so far
- In its final place
- Ruled out
function bubbleSort(a) { for (let end = a.length - 1; end > 0; end--) { 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 in order } return a;}The highlighted line is the one that produced the picture on the left.
What Bubble Sort does
Bubble sort compares each pair of neighbouring values and swaps them if they are in the wrong order. Repeat that pass often enough and the array ends up sorted, because every pass pushes the largest value still out of place all the way to the right — it bubbles up to the end.
How it works, step by step
- Walk from the left-hand end to the end of the unsorted part, comparing each bar with the one next to it.
- If the left bar is bigger, swap the pair. The bigger value carries on rightwards with you.
- When the pass finishes, the largest remaining value is in its final place, so the unsorted part shrinks by one.
- If a whole pass makes no swaps at all, nothing is out of order and the sort can stop early.
What to watch for
- The single largest bar travels all the way to the right in one pass, while everything else creeps right by at most one place.
- The comparison counter: it grows by roughly n each pass, and there are about n passes. That shape is what O(n²) means.
- Set the array to nearly sorted and the early-exit check ends the whole sort after a single clean pass.
Cost
| Best case | O(n) — one pass with no swaps |
|---|---|
| Average | O(n²) |
| Worst case | O(n²) |
| Extra space | O(1) |
| Stable | Yes |
When to reach for it
Almost never in real code — it does far more writes than insertion sort for the same work. It earns its place as the first sort people learn, because the loop is short enough to hold in your head and the quadratic growth is obvious once you have watched the counter.