Getting Started: Two Ways to Sort

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.

Race the two sorts

64

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

Why Sort at All

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.

Find one ID two ways

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.

Say it aloud

C-max equals the floor of log base two of n, plus one.

cmax
c-max the most checks binary search can need on n sorted items.
log2 n
log base two of n how many times you can halve n before you reach 1.
⌊ ⌋
the floor of round down to a whole number.
+ 1
plus one the last check, on the one item that is left.
In plain words

Halve n until one item is left, and count the halvings. Round down. Add one check for that last item.

With numbers

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.

  1. Insertion sort: grow a sorted prefix one card at a time.
  2. Loop invariants: prove the loop right for every input.
  3. Counting the cost: best, worst and the inversions in between.
  4. Merge sort: split, sort the halves, merge. The hero's bottom row.
  5. The merge: two fingers, two piles, one output.
  6. Counting inversions: let the merge count disorder for free.
  7. Where the curves cross: why the hero's sorted race goes the other way.
  8. Two ways to design: incremental and divide and conquer.
  9. Field guide: numbers, code, the lower bound and the credit.
A sorted list has 32 items. What is the most checks binary search can need?

Chapter 1

Insertion Sort

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 jKeyComparisonsShiftsArray after
2211[2, 5, 4, 6, 1, 3]
3421[2, 4, 5, 6, 1, 3]
4610[2, 4, 5, 6, 1, 3]
5144[1, 2, 4, 5, 6, 3]
6343[1, 2, 3, 4, 5, 6]
Total129sorted

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.

Step the key into place

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.

How many comparisons does insertion sort make on [5, 2, 4, 6, 1, 3]?

Chapter 2

Loop Invariants

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.

  1. Initialization. The statement is true before the first pass.
  2. Maintenance. If it is true before a pass, it is true before the next pass.
  3. Termination. When the loop stops, the statement gives the result you want.

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:

At the start of each pass j, the prefix A[1..j−1] holds the items that were first in A[1..j−1], in sorted order.

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.

Check the invariant at every pass

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].

Bug B leaves [5, 5, 4, 6, 1, 3] after pass 2. Which half of the invariant fails at the start of pass 3?

Chapter 3

Counting the Cost

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.

LineCodeTimes it runs
1for j = 2 to nn (the last test fails)
2, 3key = A[j], i = j − 1n − 1 each
4while i > 0 and A[i] > keyt2 + t3 + … + tn
5, 6shift, i = i − 1(t2 − 1) + … + (tn − 1) each
7A[i + 1] = keyn − 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).

Say it aloud

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.

S(n)
S of n the shifts insertion sort makes on n items in reversed order.
Σj=2n
the sum for j from two to n one term for each pass.
j − 1
j minus one the items left of the key in pass j. All are larger, so all shift.
n(n − 1)/2
n times n minus one, over two the total, found by pairing the first term with the last.
In plain words

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.

With numbers

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.

Say it aloud

T equals theta of n plus d.

T
T insertion sort's running time on one input.
Θ( )
theta of grows like what is inside, up to a constant factor.
n
n the number of items: each pass costs a fixed amount.
d
d the inversions in the input: pairs i < j with A[i] > A[j].
In plain words

Each of the n passes costs a fixed amount. On top, each of the d inversions costs one shift. Add the two.

With numbers

[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).

Count inversions and shifts

The curves show shifts for reversed, random and sorted input. The dot is the input you choose. Change the order and the size.

32

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.

Insertion sort runs on 100 items in reversed order. How many shifts does it make?

Chapter 4

Merge Sort

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:

  1. Divide. Split A[p..r] at the middle, q = ⌊(p + r)/2⌋.
  2. Conquer. Sort each half the same way. A piece of 0 or 1 item is already sorted, so the splitting stops there.
  3. Combine. Merge the two sorted halves (Chapter 5).
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.

Grow the recursion tree

Each row is one level of the tree. The bar on the right is the merge work of that level. Drag n.

64

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.

Say it aloud

T of n equals two T of n over two, plus c n.

T(n)
T of n the time merge sort takes on n items.
2 T(n/2)
two T of n over two the two recursive sorts, each on half the items.
c n
c n the merge: c time for each of the n items.
In plain words

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).

With numbers

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⌋.

How many levels does the recursion tree have for n = 64, counting the leaves?

Chapter 5

The Merge

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]:

kL[i] vs R[j]TakeOutput so far
12 vs 11 from R[1]
22 vs 32 from L[1, 2]
35 vs 33 from R[1, 2, 3]
45 vs 75 from L[1, 2, 3, 5]
58 vs 77 from R[1, 2, 3, 5, 7]
68 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.

Merge two piles

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.

Say it aloud

The smaller of n-one and n-two is at most C, and C is at most n-one plus n-two minus one.

C
C the comparisons one merge makes between two real items.
min(n1, n2)
the smaller of n-one and n-two the size of the shorter pile.
n1 + n2 − 1
n-one plus n-two minus one one less than the total number of items.
In plain words

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.

With numbers

[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.

How many comparisons does it take to merge [1, 2, 3] with [4, 5, 6]?

Chapter 6

Counting Inversions

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.

Say it aloud

D equals d-L plus d-R plus the sum, over each time the right pile wins, of n-one minus i.

d
d all inversions in the list.
dL
d-L inversions inside the left half, from the left recursive call.
dR
d-R inversions inside the right half, from the right recursive call.
ΣR wins
the sum over each right win one term each time the merge takes from R.
n1 − i
n-one minus i the items still waiting in L, all larger than the winner.
In plain words

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.

With numbers

[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.

Count while you merge

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.

The merge joins [1, 3, 5] and [2, 4, 6]. How many split inversions does it count?

Chapter 7

Where the Curves Cross

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.

Say it aloud

A times n squared over four equals b times n log base two of n.

a
a the time of one insertion sort step.
n2/4
n squared over four insertion sort's comparisons on random input.
b
b the time of one merge sort step, calls and copies included.
n log2 n
n log base two of n merge sort's steps: n per level, log2 n levels.
In plain words

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 numbers

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.

Find the crossover

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.

3×

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.

SituationPickWhy
A few dozen itemsInsertion sortSmallest price per step, no calls, no copies
Nearly sorted inputInsertion sortΘ(n + d) with small d
Large or hostile inputMerge sortΘ(n log n) on every input
Tight memoryInsertion sortIn place; merge sort needs n spare slots
Linked listMerge sortThe 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.

Why does Timsort sort short runs with insertion sort?

Chapter 8

Two Ways to Design an Algorithm

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).

Say it aloud

T of n equals a times T of n over b, plus f of n.

T(n)
T of n the time on n items.
a
a how many pieces each call solves.
T(n/b)
T of n over b the time on one piece, b times smaller.
f(n)
f of n the work to split the problem and combine the answers.
In plain words

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.

With numbers

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.

Compare the work per level

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).

Binary search follows T(n) = T(n/2) + 1. How many checks can it need on 1,024 sorted items?

Chapter 9

Field Guide

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.

TermMeaningNumber to remember
Binary searchHalve the sorted range each check⌊log2 n⌋ + 1 checks: 6 for 32, 20 for a million
Insertion sortSlide each key into a sorted prefix[5, 2, 4, 6, 1, 3]: 12 comparisons, 9 shifts
Loop invariantTrue each time the loop test runsInitialization, maintenance, termination
Worst caseReversed inputn(n − 1)/2 shifts: 28 for n = 8
InversionA pair in the wrong orderShifts = inversions; random input has n(n − 1)/4
Merge sortSplit, sort halves, mergelog2 n + 1 levels; 192 comparisons on 64 sorted items
MergeTwo fingers over two sorted pilesmin(n1, n2) to n1 + n2 − 1 comparisons
StableEqual items keep their orderInsertion: shift on >. Merge: take left on ≤
CrossoverSize where merge sort starts to winA few dozen items: with a 3× step price, 75 by the formula, about 50 measured

Checklist

The core, as code

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:]

The floor no comparison sort can beat

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.

Sorts you already use

LibrarySortBuilt from
Python sorted()Timsort, stableInsertion sort on short runs, then merges
Java, object arraysTimsort, stableThe same
C++ std::stable_sortMerge sort, stableMerge sort with a spare buffer
C++ std::sortIntrosort, not stableQuicksort, heapsort, insertion sort for small pieces

Keep going

The takeaway. Count before you guess. The step count gives the growth, the price per step gives the crossover, and the loop invariant gives the proof.
You must sort 50 items that are already almost in order. Which sort, and why?

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.

Credit and source

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.

CLRS Chapter 2: Getting Started
Next: Growth of Functions · Back to Gleams