Sorting

The same sixteen numbers, sorted seven ways. Watch which pairs each one compares and moves, then race them all on four kinds of data.

Level: BasicWatch: 16 steps · ~2 min7 algorithms × 4 kinds of dataRecall: 3 questions · 8 cardsCompare all sevenTypeScript · Go · Python

What you'll take away

  • Work out what doubling the data does to an n² sort and to an n log n one
  • Pick insertion sort for nearly sorted data, and a random pivot so quick sort stays fast
  • Know which sorts are stable, and why that matters when you sort by two keys
  • Use your language's sort, and counting sort only for a small range of whole numbers

The 1-minute version

Tap a point and the picture below plays that step.

4Compare them all
Bubble sortRandom · swap neighbours
11315414271161269138510
pass 1 · places 1–16compared 0 · moved 0
11 > 3
Pass 1, pair by pair → …
Step 1 / 16 · step by step
110Comparisons
59Moves
499,065Comparisons at 1,000
O(n²)Average time
O(1)Extra memory

The picture: the sixteen numbers are sixteen towers in a row on one street, as tall as their value. The pair being compared is lit purple, a tower on the move amber, and a tower in its final place gets a blue roof. Each step plays one thing: one pass, one insert, one merge, one split around a pivot (gold), the heap's build or one pull from it (the family being sifted is drawn on the pavement), the tally or the write. Merge sort lifts the stretch it merges onto a side street in front (its extra memory); counting sort stacks a tally pile per value there and raises new towers from it. Each algorithm really runs on these numbers; the counts are its own.

Step 4 · Every option at once, on one clock

Compare them all: Sorting

The same 16 numbers in every tile (random). Every way takes one step of work per tick, so the one with less work finishes first.

0 steps
Bubble sortO(n²) · extra O(1)so far 0 steps

Use it when Teaching, or a handful of items that are nearly sorted (it can stop after a pass with no swap)

Skip it when Real data of any size: about n²/2 comparisons

The counts are the comparisons and moves each algorithm really makes on these numbers, not a timing. Press any tile to see it large above, with when it fits.

Big-O, side by side

AverageWorstExtra memoryStableComparisons at 1,000
Bubble sortO(n²)O(n²)O(1)yes499,065
Insertion sortO(n²)O(n²)O(1)yes250,852
Merge sortO(n log n)O(n log n)O(n)yes8,690
Quick sortO(n log n)O(n²)O(log n)no10,189
Heap sortO(n log n)O(n log n)O(1)no16,855
Counting sortO(n + k)O(n + k)O(n + k)yes0
Radix sortO(d·(n + b))O(d·(n + b))O(n + b)yes0

n is the number of items, k the range of values, d the number of digits, b the base. Quick sort's O(log n) is the stack on average. Comparisons at 1,000 are counted on one fixed shuffle of 1,000 numbers.

What n² means

Double the data and an n² sort does four times the work; n log n does a little over twice. At sixteen items the gap is small. At a thousand, bubble sort compares about 500,000 times and merge sort about 9,000.

In practice

Use your language's sort. It is already a careful mix: Timsort (Python, V8) runs insertion sort on small pieces and merges them; Go's pdqsort is a quick sort that falls back to insertion sort for small pieces and heap sort when its splits go bad. Write your own only for a special shape of data, like counting sort for a small range of whole numbers.

In real code

builtins.ts
/// <reference lib="es2023.array" />
// The built-in sort in JavaScript / TypeScript: three things that catch people.
// Run: node builtins.ts   (Node 23.6+; on Node 22: node --experimental-strip-types builtins.ts)
import assert from "node:assert/strict";

// 1. With no comparator, sort() compares the items as strings: 10 comes before 9.
const prices = [100, 9, 10, 1];
assert.deepEqual([...prices].sort(), [1, 10, 100, 9]);
assert.deepEqual([...prices].sort((a, b) => a - b), [1, 9, 10, 100]);

// 2. sort() changes the array itself; toSorted() (ES2023) returns a new one.
const kept = [3, 1, 2];
const copy = kept.toSorted((a, b) => a - b);
assert.deepEqual(kept, [3, 1, 2]);
assert.deepEqual(copy, [1, 2, 3]);

// 3. It is stable (required since ES2019): equal keys keep their order, so sorting by a second key keeps the first.
const orders = [
  { id: "A", city: "Chiang Mai" }, { id: "B", city: "Bangkok" }, { id: "C", city: "Chiang Mai" }, { id: "D", city: "Bangkok" },
];
const byCity = orders.toSorted((x, y) => x.city.localeCompare(y.city));
assert.deepEqual(byCity.map((o) => o.id), ["B", "D", "A", "C"]);

console.log(`[100, 9, 10, 1].sort() → [${[...prices].sort()}] · with (a, b) => a - b → [${[...prices].sort((a, b) => a - b)}] · stable by city: ${byCity.map((o) => o.id).join("")}`);
Run: node builtins.ts (Node 23.6+ · on Node 22 add --experimental-strip-types)It printed: [100, 9, 10, 1].sort() → [1,10,100,9] · with (a, b) => a - b → [1,9,10,100] · stable by city: BDAC

What you use every day: JavaScript compares as strings unless you pass a comparator, and its sort is stable; Python's sorted() takes a key; Go has slices.Sort and slices.SortStableFunc. Each really runs.

Common questions

How big is the gap between O(n²) and O(n log n), really?

Double the data and n² does four times the work, n log n a little over twice. At 16 items you barely see it; at 1,000, bubble sort compares about 500,000 times and merge sort about 9,000.

Which sort is best for data that's nearly sorted?

Insertion sort: each item slides only a little, so it's about n steps. On 1,000 nearly sorted items it compares about a thousand times; merge sort still needs about five thousand.

When is quick sort at its worst, and what's the fix?

When the pivot doesn't split near the middle, like the last item on already sorted data: n². Pick the pivot at random or as the median of three; some library sorts (C++'s introsort, Go's pdqsort) also switch to heap sort when the splits keep going bad.

What's a stable sort, and why does it matter?

Equal values keep their order. Sort orders by date, then by city, and within each city they're still by date. Merge, insertion and counting sort are stable; quick and heap sort aren't.

Table: Big-O, side by side

Merge sort is n log n every time. What's the catch?

A side buffer as big as the data, O(n). In return it's stable, and it can sort data bigger than memory by sorting chunks and merging them.

Counting sort needs no comparisons. Why not use it everywhere?

It only works for whole numbers in a small range, like scores 0–100: it needs a counter for every possible value. A wide range, or data that isn't small integers, and you're back to comparing.

Why does [10, 9, 1, 100].sort() come out wrong in JavaScript?

With no comparator it turns every item into a string and compares them letter by letter, giving [1, 10, 100, 9]. Pass (a, b) => a - b. Python and Go compare numbers as numbers.

Should I write my own sort?

Almost never. Your language's sort is already a careful mix: Timsort (Python, V8) runs insertion sort on small pieces and merges them, and Go uses pdqsort. Write your own only for a special shape of data, like counting sort for a small range.

Next lesson

Database indexesLevel: Intermediate

Sorting costs n log n each time; next, how a B-tree index keeps rows in order, so the database finds one without reading them all.