Sort 64 shuffled numbers. Insertion sort makes about 1,070 comparisons and merge sort about 305. Hand both a list that is already sorted, and insertion sort wins, 63 to 192.
Pick an input and a size, then press Race. Both sorts get the same numbers. Then we build both sorts from zero, prove one correct, count the cost line by line, and find where the two curves cross.
You need Python loops and lists. We build the rest from zero.
Based on Chapter 2, "Getting Started", of Introduction to Algorithms (CLRS) by Thomas H. Cormen, Charles E. Leiserson, Ronald L. Rivest and Clifford Stein (MIT Press). The pseudocode follows the book's third edition. The explanations, toys and devices are our own.
A comparison is one test of two values. Counts are exact for this seeded input. The lede's random numbers are averages over many shuffles.
Chapter 0
See how sorted order turns ten thousand checks into fourteen
You have 10,000 student IDs and one ID to find. If the list is in random order, you check the entries one by one. That takes 5,000 checks on average and 10,000 in the worst case.
If the list is sorted, open it at the middle. Is your ID bigger than the middle entry? Then the whole left half is out. Repeat on the half that is left. This is binary search: each check halves the part of the list that can still hold the ID.
Top row: the IDs in random order, scanned left to right. Bottom row: the same IDs sorted, searched from the middle. Pick a target and press Search.
A toy list of 32 two-digit IDs. A check is one look at one entry.
How many checks can binary search need? Call the number of items n. Count how many times you can halve n before one item is left.
C-max equals the floor of log base two of n, plus one.
Halve n until one item is left, and count the halvings. Round down. Add one check for that last item.
For n = 32, log2 32 = 5, so c-max = 6. For n = 1,000,000, log2 n = 19.93, so c-max = 20. A scan of the same million can need a million checks.
Sorting is not free. Merge sort, later in this lesson, sorts a million items in about 20 million steps.
Now run 1,000 searches. Without sorting, that costs 1,000 × 1,000,000 = 1 billion checks. With sorting, it costs 20 million + 1,000 × 20, about 20 million. Sorting first saves about 98% of the work. It pays for itself after about 20 searches.
Failure. Binary search says "not found" for an ID that is in the list. Measure: walk the list once and check that each entry is no larger than the next. Fix: sort before you search, and keep the list sorted when you add to it.
This lesson follows Chapter 2 of CLRS. It gives two ways to sort and the tools to judge any algorithm.
Chapter 1
Slide each new item left past the larger ones, the way you sort a hand of cards
Pick up cards one at a time. Slide each new card left past every larger card in your hand, then drop it into the gap. Your hand is always sorted. The table holds the rest.
That is insertion sort. The left part of the array is the sorted prefix. The item being placed is the key. Each pass takes the next key and moves larger items one place right. Each move is a shift. The pass stops when the item on the key's left is not larger.
CLRS pseudocode, indexes from 1INSERTION-SORT(A, n) for j = 2 to n key = A[j] // the item to place i = j - 1 while i > 0 and A[i] > key // a comparison is one test of A[i] > key A[i + 1] = A[i] // shift right i = i - 1 A[i + 1] = key // drop the key into the gap
Trace it on [5, 2, 4, 6, 1, 3]. A comparison is one test of A[i] > key.
| Pass j | Key | Comparisons | Shifts | Array after |
|---|---|---|---|---|
| 2 | 2 | 1 | 1 | [2, 5, 4, 6, 1, 3] |
| 3 | 4 | 2 | 1 | [2, 4, 5, 6, 1, 3] |
| 4 | 6 | 1 | 0 | [2, 4, 5, 6, 1, 3] |
| 5 | 1 | 4 | 4 | [1, 2, 4, 5, 6, 3] |
| 6 | 3 | 4 | 3 | [1, 2, 3, 4, 5, 6] |
| Total | 12 | 9 | sorted |
Each shift costs one comparison. Passes 3, 4 and 6 also make one comparison that stops the key. Passes 2 and 5 stop at the left edge, where the test i > 0 fails first. So 9 shifts cost 9 + 3 = 12 comparisons.
Orange is the key. Teal is the sorted prefix. A yellow outline marks the item that the comparison tests against the key. Press Step, or Play.
Toy inputs. The counts are exact.
In Python, indexes start at 0, so the loop starts at 1 and the edge test is i >= 0.
pythondef insertion_sort(A): # A: list of numbers, sorted in place for j in range(1, len(A)): key = A[j] # save the key first i = j - 1 while i >= 0 and A[i] > key: # strict > keeps equal items in order A[i + 1] = A[i] # shift right i -= 1 A[i + 1] = key return A
Failure. Some items vanish and others appear twice. The cause is a shift that runs before the code saves the key, so the first shift overwrites the key. Measure: compare sorted(input) with the output. Fix: set key = A[j] before the loop.
Insertion sort needs only the key as extra memory, so it is in place. It is stable: equal items keep their input order, because the loop shifts only items strictly larger than the key.
Chapter 2
Prove that the loop is right for every input, and use the proof to find bugs
A test on ten lists shows that the sort works on those ten lists. A proof shows that it works on every list. CLRS proves loops with a loop invariant: a statement that is true each time the loop test runs.
The first two parts are a proof by induction. The third part is new: the loop must stop, and the statement must then say the job is done.
The invariant of insertion sort's outer loop:
The words "the items that were first there" matter. Without them, a loop that fills the array with copies of one value would pass. The device has that bug.
Each row is the array at the start of a pass. Teal marks the prefix. Pick a version of the code and press Step to test both halves of the invariant.
The input is [5, 2, 4, 6, 1, 3]. The code is the 0-based Python of Chapter 1; the bugs are two common slips.
The proof. Initialization: before pass 2 the prefix is A[1] alone, so it is sorted and holds its own item. Maintenance: a pass moves the larger items right and drops the key in the gap, so A[1..j] is sorted and holds the same items. Termination: the loop stops at j = n + 1, so the prefix A[1..n] is the whole array, sorted.
Failure. A sort gives wrong output on one list in a thousand. Measure: assert the invariant at the top of the loop, and find the first pass where it breaks. Fix the line that runs in that pass. With Bug A the check fails at the start of pass 3: [5, 2] is not sorted, because while i > 0 never compares the key with A[0].
Chapter 3
Count how often each line runs, and find what decides the cost between best and worst
CLRS times an algorithm by counting. Each simple step, such as a comparison or an assignment, costs a fixed time. This is the RAM model. Count how often each line runs, multiply by its cost, and add.
| Line | Code | Times it runs |
|---|---|---|
| 1 | for j = 2 to n | n (the last test fails) |
| 2, 3 | key = A[j], i = j − 1 | n − 1 each |
| 4 | while i > 0 and A[i] > key | t2 + t3 + … + tn |
| 5, 6 | shift, i = i − 1 | (t2 − 1) + … + (tn − 1) each |
| 7 | A[i + 1] = key | n − 1 |
Here tj is how many times the while test runs in pass j. On sorted input tj = 1: one failed test, no shift, so the time grows in a straight line with n. On reversed input the key passes every item before it, so tj = j. How many shifts is that? Call the worst-case shift count S(n).
S of n equals the sum, for j from two to n, of j minus one, which equals n times n minus one, over two.
In pass j the key moves past all j − 1 items before it. Add those counts over every pass. The sum 1 + 2 + … + (n − 1) is n(n − 1)/2.
For n = 6: 1 + 2 + 3 + 4 + 5 = 15 = 6 × 5 / 2. For n = 8: S = 28 shifts and 28 comparisons. The while test also fails 7 times at the left edge, so t2 + … + t8 = 35. For n = 100: 4,950 shifts.
CLRS keeps only the fastest growing term and drops the constants. That is the order of growth. Insertion sort is Θ(n2) in the worst case and Θ(n) in the best. Θ, said "theta", means "grows like, up to a constant factor".
What decides the cost in between? An inversion is a pair of items in the wrong order: an earlier item larger than a later one. Each shift moves the key past one larger item, so it fixes exactly one inversion. Call the number of inversions d.
T equals theta of n plus d.
Each of the n passes costs a fixed amount. On top, each of the d inversions costs one shift. Add the two.
[5, 2, 4, 6, 1, 3] has d = 9 inversions and took 9 shifts in Chapter 1. Sorted input has d = 0. Reversed input has every pair inverted: d = n(n − 1)/2, which is S(n).
The curves show shifts for reversed, random and sorted input. The dot is the input you choose. Change the order and the size.
Seeded toy inputs. Random input has n(n − 1)/4 inversions on average.
Failure. A sort that is fast in tests is slow in production. Measure: count the inversions in real inputs, or time the sort on reversed data. Fix: always test the worst case, and above a few dozen items use merge sort.
Chapter 4
Split the list in half, sort each half the same way, and merge the sorted halves
Insertion sort is slow because each key moves one step at a time. Try another plan. Take two sorted piles of exam papers. Compare the two top papers and take the smaller, again and again. You touch each paper once. And a pile of one paper is already sorted.
That plan is divide and conquer:
CLRS pseudocodeMERGE-SORT(A, p, r) if p < r // two or more items q = floor((p + r) / 2) MERGE-SORT(A, p, q) // sort the left half MERGE-SORT(A, q + 1, r) // sort the right half MERGE(A, p, q, r) // merge them
Draw the calls as a recursion tree. Level 0 holds one piece of n items. Level 1 holds two pieces of n/2, and level k holds 2k pieces of n/2k. At every level, the merges touch all n items once.
Each row is one level of the tree. The bar on the right is the merge work of that level. Drag n.
One unit of work is one item moved by a merge. The leaves do no merging.
How long does merge sort take? Call the time to sort n items T(n), and the merge cost per item c.
T of n equals two T of n over two, plus c n.
To sort n items, sort two halves and merge. Unroll it as the tree: each of the log2 n merge levels costs c n. So T(n) = c n log2 n + c n, which is Θ(n log n).
For n = 64: log2 64 = 6 merge levels, each moving 64 items, so 384 moves. The leaves make a seventh level. For n = 1,000,000: n log2 n is about 20 million steps.
Insertion sort's worst case on a million items is n2/2 = 500 billion steps, 25,000 times more. At a billion steps a second, that is 8 minutes against 0.02 seconds. Merge sort pays that price on every input, because it always splits in half. It also needs n spare slots for the merge.
Failure. Merge sort never returns, or the stack overflows. The cause is a midpoint rounded up, which splits two items into two and zero, or a base case if p == r that misses empty ranges. Measure: print the range size at each call. Fix: if p >= r: return and q = ⌊(p + r)/2⌋.
Chapter 5
Combine two sorted piles with two fingers, and count what that costs
Two sorted piles lie face up. Keep a finger on the top of each. Compare the two tops, move the smaller to the output, and move that finger down. When one pile is empty, move the rest of the other.
CLRS puts a sentinel at the bottom of each pile: a card worth ∞. It never beats a real card, so the loop never checks for an empty pile. The loop runs exactly once for each output slot.
CLRS pseudocodeMERGE(A, p, q, r) n1 = q - p + 1; n2 = r - q copy A[p..q] into L[1..n1], A[q+1..r] into R[1..n2] L[n1 + 1] = ∞; R[n2 + 1] = ∞ // sentinels i = 1; j = 1 for k = p to r if L[i] <= R[j] // <= : ties go left A[k] = L[i]; i = i + 1 else A[k] = R[j]; j = j + 1
Merge L = [2, 5, 8] with R = [1, 3, 7]:
| k | L[i] vs R[j] | Take | Output so far |
|---|---|---|---|
| 1 | 2 vs 1 | 1 from R | [1] |
| 2 | 2 vs 3 | 2 from L | [1, 2] |
| 3 | 5 vs 3 | 3 from R | [1, 2, 3] |
| 4 | 5 vs 7 | 5 from L | [1, 2, 3, 5] |
| 5 | 8 vs 7 | 7 from R | [1, 2, 3, 5, 7] |
| 6 | 8 vs ∞ | 8 from L | [1, 2, 3, 5, 7, 8] |
Five comparisons between real items. The sixth test is against the sentinel, and code without sentinels skips it.
Blue is the left pile, purple the right. Each output item keeps its colour, so you see where it came from. Pick two piles and press Step.
Toy piles. ∞ marks a sentinel. The count includes only comparisons between two real items.
How many comparisons can one merge need? Call the pile sizes n1 and n2, and the count C.
The smaller of n-one and n-two is at most C, and C is at most n-one plus n-two minus one.
Each comparison sends one item out. When one pile empties, the rest copies with no comparisons. The fewest: the shorter pile is wholly smaller and empties first. The most: the piles interleave, so both last until one item is left.
[1, 2, 3] with [4, 5, 6]: C = 3 = min(3, 3). [1, 3, 5] with [2, 4, 6]: C = 5 = 3 + 3 − 1. The table's merge also takes 5.
On a tie, MERGE takes from the left, because the test is L[i] ≤ R[j]. Left items came first in the input, so equal items keep their order: merge sort is stable. Change ≤ to < and it is not.
Failure. You sort orders by city, then sort them by date, and the cities come out shuffled within each date. Measure: sort pairs that share a key and check their order. Fix: take from the left on ties.
Chapter 6
Let the merge count how far a list is from sorted, in n log n time
Two friends rank the same five films. How different are their tastes? Write one friend's ranking in the order of the other's and count the inversions. That count is the Kendall tau distance: 0 for the same ranking, n(n − 1)/2 for opposite rankings.
Checking every pair takes n(n − 1)/2 comparisons. Merge sort can count while it sorts. Every inversion is one of three kinds: both items in the left half, both in the right half, or one in each half. The last kind is a split inversion.
The first two kinds come back from the recursive calls. Split inversions show up in the merge. When the right pile wins, its item is smaller than every item still in the left pile, because L is sorted. Call the items already taken from L i. Then the winner jumps n1 − i items at once.
D equals d-L plus d-R plus the sum, over each time the right pile wins, of n-one minus i.
Take d-L and d-R from the two recursive calls. During the merge, each time R wins, add the number of items still in L. The total is d.
[2, 4, 1, 3, 5] splits into [2, 4] and [1, 3, 5], so d-L = 0 and d-R = 0. In the merge, 1 wins with i = 0: add 2. Then 3 wins with i = 1: add 1. So d = 0 + 0 + 2 + 1 = 3.
Yellow arcs show the left items a right winner jumps. Each arc is one split inversion. Pick two halves and press Step.
Toy halves, already sorted, as the recursive calls return them.
Failure. The count comes out too low. The cause is adding 1 each time R wins, not n1 − i. On [2, 4, 1, 3, 5] that gives 2, not 3. Measure: compare with a brute-force pair count on small random lists. Fix: add n1 − i.
Chapter 7
Price each step and find the size where merge sort starts to win
Chapters 3 and 4 counted steps. A real machine charges a different price per step. An insertion sort step is a tight loop over neighbouring memory. A merge sort step also pays for function calls and for copies into spare arrays.
So the winner depends on n and on those prices. Call the time of one insertion sort step a and of one merge sort step b. On random input, insertion sort makes about n2/4 comparisons and merge sort about n log2 n.
A times n squared over four equals b times n log base two of n.
The left side is insertion sort's time, the right side merge sort's. Solve for n. Below that n, the left side is smaller and insertion sort wins.
With made-up prices a = 1 and b = 3: at n = 64, 1,024 against 1,152, so insertion sort wins. At n = 128, 4,096 against 2,688, so merge sort wins. The sides meet near n = 75.
Orange is insertion sort, teal is merge sort. Each line multiplies the measured comparisons by the price of a step. Drag the price of a merge step and change the input.
The page counts comparisons live on seeded inputs; random input averages 12 shuffles. The price ratio is a knob, not a measurement: it depends on the language and the machine.
The measured crossing comes earlier than the formula's, near n = 50. Merge sort makes fewer comparisons than n log2 n: on random input, about n log2 n − 1.25n.
Now pick Sorted. Insertion sort makes n − 1 comparisons and merge sort about (n/2) log2 n, so insertion sort wins at every size. Reversed input moves the crossing left.
Real sorts use both. CLRS Problem 2-1 sorts pieces of k items with insertion sort, then merges the pieces, in Θ(nk + n log(n/k)) time. Timsort, the sort in Python and Java, does the same with runs of 32 to 64 items.
| Situation | Pick | Why |
|---|---|---|
| A few dozen items | Insertion sort | Smallest price per step, no calls, no copies |
| Nearly sorted input | Insertion sort | Θ(n + d) with small d |
| Large or hostile input | Merge sort | Θ(n log n) on every input |
| Tight memory | Insertion sort | In place; merge sort needs n spare slots |
| Linked list | Merge sort | The merge needs no random access |
Failure. A hybrid sort with a cutoff of k = 1,000 runs slower than plain merge sort. Measure: time the sort for several values of k. Fix: set k near the measured crossover, a few dozen items.
Chapter 8
Grow a valid answer one item at a time, or split the problem and combine the answers
Insertion sort and merge sort are two shapes that most algorithms take. An incremental algorithm keeps a valid partial answer and folds in one item at a time. A divide-and-conquer algorithm splits the problem into smaller problems of the same kind, solves each, and combines the answers.
An incremental algorithm costs n times the price of one fold. Insertion sort's fold costs up to j shifts, so the total is quadratic. Keeping the largest item seen so far costs one comparison per fold, so that total is linear.
A divide-and-conquer algorithm has a recurrence: its time on n items, written with its time on smaller pieces. Call the number of pieces a, the shrink factor b, and the cost to split and combine f(n).
T of n equals a times T of n over b, plus f of n.
Solve a pieces, each b times smaller, then pay f(n) to combine. Unroll it as a tree and add the work of every level.
Binary search: a = 1, b = 2, f = 1, so n = 64 takes 7 checks, one per level. Merge sort: a = 2, b = 2, f(n) = n, so each of the 7 levels does 64 units: 448.
Each bar is the work of one level of the tree for n = 64, scaled to the largest level. Pick a problem.
A level's work is f(size) summed over its pieces. Strassen multiplies matrices with 7 half-size products and f(n) = n2 (CLRS Chapter 4). Counts are exact for n = 64.
Three shapes appear. If each level does the same work, the total is that work times the number of levels: merge sort's n log n. If the work grows down the tree, the leaves decide: Strassen has 7log2 n = n2.81 of them. If only one piece survives each split, the total is the depth: binary search's log n.
Failure. A divide-and-conquer solution runs slower than brute force. Measure: write the recurrence and look at the work per level. Two causes are common: a combine step that costs n2 or more, or pieces that overlap, so the code solves one subproblem many times. Fix: a cheaper combine, or store each answer once (dynamic programming, CLRS Chapter 15).
Chapter 9
Keep the numbers, the checks and the code in one place
Insertion sort grows a sorted prefix, and a loop invariant proves it right. Counting lines gives Θ(n) on sorted input, Θ(n2) on reversed input, and Θ(n + d) in between. Merge sort halves, recurses and merges in Θ(n log n) on every input, at the cost of n spare slots. The price per step decides small sizes, so real sorts mix the two.
| Term | Meaning | Number to remember |
|---|---|---|
| Binary search | Halve the sorted range each check | ⌊log2 n⌋ + 1 checks: 6 for 32, 20 for a million |
| Insertion sort | Slide each key into a sorted prefix | [5, 2, 4, 6, 1, 3]: 12 comparisons, 9 shifts |
| Loop invariant | True each time the loop test runs | Initialization, maintenance, termination |
| Worst case | Reversed input | n(n − 1)/2 shifts: 28 for n = 8 |
| Inversion | A pair in the wrong order | Shifts = inversions; random input has n(n − 1)/4 |
| Merge sort | Split, sort halves, merge | log2 n + 1 levels; 192 comparisons on 64 sorted items |
| Merge | Two fingers over two sorted piles | min(n1, n2) to n1 + n2 − 1 comparisons |
| Stable | Equal items keep their order | Insertion: shift on >. Merge: take left on ≤ |
| Crossover | Size where merge sort starts to win | A few dozen items: with a 3× step price, 75 by the formula, about 50 measured |
p >= r, and round the midpoint down.pythondef insertion_sort(A): for j in range(1, len(A)): key, i = A[j], j - 1 while i >= 0 and A[i] > key: A[i + 1] = A[i]; i -= 1 A[i + 1] = key def merge_sort(A): # returns a new sorted list if len(A) <= 1: return A mid = len(A) // 2 L, R = merge_sort(A[:mid]), merge_sort(A[mid:]) out, i, j = [], 0, 0 while i < len(L) and j < len(R): if L[i] <= R[j]: out.append(L[i]); i += 1 # ties go left: stable else: out.append(R[j]); j += 1 return out + L[i:] + R[j:]
Each comparison has two outcomes, so k comparisons can tell apart at most 2k orders. There are n! orders of n items. So a sort that only compares needs at least log2(n!) comparisons in the worst case, about n log2 n. For n = 64 that floor is 296, and merge sort's worst case is 321. CLRS proves this in Chapter 8.
| Library | Sort | Built from |
|---|---|---|
Python sorted() | Timsort, stable | Insertion sort on short runs, then merges |
| Java, object arrays | Timsort, stable | The same |
C++ std::stable_sort | Merge sort, stable | Merge sort with a spare buffer |
C++ std::sort | Introsort, not stable | Quicksort, heapsort, insertion sort for small pieces |
Now press Present or Teach and explain three things from memory. Give the invariant of insertion sort. Say why reversed input costs n(n − 1)/2 shifts, and why every level of merge sort costs n. Then go back to the race, pick Sorted, and say why insertion sort wins.
This lesson re-teaches Chapter 2, "Getting Started", of Introduction to Algorithms by Thomas H. Cormen, Charles E. Leiserson, Ronald L. Rivest and Clifford Stein, published by MIT Press. The pseudocode follows the third edition, with indexes from 1 and sentinels in MERGE. The toys, counts and devices are our own; we checked every count on this page by running the code.