Skip to content

Merge sort

ordering

Level 2 of 3

Also called Bottom-up merge sort.

how it works

The idea and three pictures, then one row sorted step by step.

Merge sort puts a row of numbers in order, smallest first. A run is a part of the row in order, and one number alone is a run. A merge joins two runs. It places the smaller front into a second row, the left one on a tie. When one run is used up, the rest of the other follows with no comparison. Round 1 merges runs of 1 in pairs from the left, round 2 runs of 2, and on, building bottom up until one run holds the row. A run with no partner waits. The steps below draw each merge in the one row.

the row: 42, 7, 31, 18, 56, 23, 12, 4911111111start2222round 144round 28round 32a run, its length insidethe first runall in one runa merge in round 2, its numbers74218317183142goes straight in, the other run used up
The steps below, as rounds. Round 2 merges 7, 42 with 18, 31, made in round 1.
roundrun lengthmergescomparisonsplaced
11448
22268
34168
in all71624
3 rounds, as 8 = 2 × 2 × 2, so the log of 8 is 3; each places all 8, so 8 × 3 = 24.
3a13b2start13a3b2merge 113a23bmerge 2123a3bmerge 3
Thick lines follow the two 3s, dotted lines the other numbers. In merge 3 they tie; the left goes first, so 3a stays in front.
A short shuffle: 8 moments of its 44 steps, the steps between them left for the watch page
  1. step 1 of 44

    427311856231249

    There are 8 numbers in a row. Each one on its own is a run in order.

    what it remembers to know where it is
    run length
    not yet
    front of the left run
    not yet
    front of the right run
    not yet

    Where it says not yet, nothing is held there at that moment.

    watch from here

  2. step 4 of 44

    427311856231249

    7 is smaller than 42, so 7 goes next.

    what it remembers to know where it is
    run length
    1
    front of the left run
    42
    front of the right run
    7

    watch from here

  3. step 5 of 44

    742311856231249

    7 moves in front of 42, and the left run moves one place right to make room.

    what it remembers to know where it is
    run length
    1
    front of the left run
    42
    front of the right run
    7

    watch from here

  4. step 18 of 44

    742183123561249

    Merge neighbouring runs of up to 2 numbers into runs of up to 4.

    what it remembers to know where it is
    run length
    2
    front of the left run
    not yet
    front of the right run
    not yet

    Where it says not yet, nothing is held there at that moment.

    watch from here

  5. step 33 of 44

    718314212234956

    Merge neighbouring runs of up to 4 numbers into runs of up to 8.

    what it remembers to know where it is
    run length
    4
    front of the left run
    not yet
    front of the right run
    not yet

    Where it says not yet, nothing is held there at that moment.

    watch from here

  6. step 37 of 44

    712183142234956

    12 moves in front of 18, and the left run moves one place right to make room.

    what it remembers to know where it is
    run length
    4
    front of the left run
    18
    front of the right run
    12

    watch from here

  7. step 43 of 44

    712182331424956

    One run is used up, so the 2 numbers left in the other follow as they stand.

    what it remembers to know where it is
    run length
    4
    front of the left run
    not yet
    front of the right run
    not yet

    Where it says not yet, nothing is held there at that moment.

    watch from here

  8. step 44 of 44

    712182331424956

    In order, after 16 comparisons, with 24 numbers placed into merged runs.

    what it remembers to know where it is
    run length
    not yet
    front of the left run
    not yet
    front of the right run
    not yet

    Where it says not yet, nothing is held there at that moment.

    watch from here

the steps, in plain words
  1. every number on its own is a run in orderPython lines 12, 13 and 15
  2. while there is more than one runPython lines 16, 40, 41 and 42
  3. merge each neighbouring pair of runs into onePython lines 11, 14, 17, 18, 19, 20 and 21
  4. compare the fronts of the two runsPython lines 23 and 24
  5. the smaller goes next, the left one if they are equalPython lines 25, 26, 27, 28, 29 and 30
  6. when one run is used up, the rest of the other followsPython lines 32, 33, 34, 35, 36, 37, 38 and 39
the same in Python

The steps in plain words are what to learn. Python is a programming language, and the code below does the same steps, for those who code. Python numbers the places in a list from 0, not 1: the first number is numbers[0], the second numbers[1], and so on.

def merge_sort(numbers):
    """Put a list of numbers in order, smallest first, ending in the same list.

    Every number on its own is a run in order. Neighbouring runs are merged
    into runs twice as long, round after round, until one run holds the
    whole list. Each round writes into a second list as long as the first,
    made once and used again every round, so the sort needs that much room
    again. On a tie the number from the left run goes first, so equal
    numbers keep the order they came in.
    """
    n = len(numbers)
    if n < 2:  # one number, or none, is already in order
        return numbers
    merged = [None] * n  # the second list, used again every round
    width = 1  # every number on its own is a run in order
    while width < n:  # while there is more than one run
        for start in range(0, n, 2 * width):  # each pair of runs,
            # or a last run with no partner, copied across as it stands
            middle = min(start + width, n)
            end = min(start + 2 * width, n)
            i, j, k = start, middle, start  # the two fronts, the next place

            while i < middle and j < end:  # compare the two fronts
                if numbers[j] < numbers[i]:  # the smaller goes next,
                    merged[k] = numbers[j]
                    j += 1
                else:  # the left one if they are equal
                    merged[k] = numbers[i]
                    i += 1
                k += 1

            while i < middle:  # one run is used up: the rest of the other
                merged[k] = numbers[i]
                i += 1
                k += 1
            while j < end:
                merged[k] = numbers[j]
                j += 1
                k += 1
        for k in range(n):  # the round's runs, twice as long, copied back
            numbers[k] = merged[k]
        width *= 2
    return numbers

how it scales

How the comparisons grow, from ten numbers to ten million.

Each step across or up is ten times the one before, a log-log plot. The lines climb a little more than one step up for each step across, as n log⁡2 nn \,\log_2\, n outgrows nn. The shuffled points, the mean of 20 shuffles each, lie just under the dearest line.

comparisons, ten times more at each mark up

a secondslope 1.1102104106108101102103104105106107a secondslope 1.1101102103104105106107108109101102103104105106107a secondslope 1.1101102103104105106107108109101102103104105106107

nn, how many numbers are in the row, ten times more at each mark to the right

  • a dearest row, where every merge compares all but its last numbersolid where measured by running it; dashed where its formula carries it on to ten millionslope 1.1: ten times n, 12 times the work
  • shuffled, every order of different numbers as likelypoints only, each measured by a real run, since no single formula for the comparisons of this row is worked out here
  • different numbers back to front, a cheapest rowsolid where measured by running it; dashed where its formula carries it on to ten million
what a dearest row costs, at a billion comparisons a second
nncomparisonstime
1,0008,985about 9 microseconds
100,0001,592,993about 1.6 milliseconds
10,000,000226,648,193about 227 milliseconds

The comparisons are the same on any computer. The times are not: a real computer may be faster or slower than a billion a second.

make these counts yourself

Copy this script and run it with Python 3.12 or later. It counts the same steps as the plot. Where a count depends on a random shuffle, yours will differ a little.

"""Count merge sort's comparisons yourself, as the plot on this page does.

Run it with Python 3.12 or later. For each size n it prints the comparisons
on a row back to front (a cheapest row), on a row already in order, and the
average over 20 shuffles. The counts are the same on any computer; only the
time taken differs.
"""
import random


class Counted:
    """A number that counts every comparison made with it."""

    comparisons = 0

    def __init__(self, value):
        self.value = value

    def __lt__(self, other):
        Counted.comparisons += 1
        return self.value < other.value


def merge_sort(numbers):
    """Put a list of numbers in order, smallest first, ending in the same list.

    Every number on its own is a run in order. Neighbouring runs are merged
    into runs twice as long, round after round, until one run holds the
    whole list. Each round writes into a second list as long as the first,
    made once and used again every round, so the sort needs that much room
    again. On a tie the number from the left run goes first, so equal
    numbers keep the order they came in.
    """
    n = len(numbers)
    if n < 2:  # one number, or none, is already in order
        return numbers
    merged = [None] * n  # the second list, used again every round
    width = 1  # every number on its own is a run in order
    while width < n:  # while there is more than one run
        for start in range(0, n, 2 * width):  # each pair of runs,
            # or a last run with no partner, copied across as it stands
            middle = min(start + width, n)
            end = min(start + 2 * width, n)
            i, j, k = start, middle, start  # the two fronts, the next place

            while i < middle and j < end:  # compare the two fronts
                if numbers[j] < numbers[i]:  # the smaller goes next,
                    merged[k] = numbers[j]
                    j += 1
                else:  # the left one if they are equal
                    merged[k] = numbers[i]
                    i += 1
                k += 1

            while i < middle:  # one run is used up: the rest of the other
                merged[k] = numbers[i]
                i += 1
                k += 1
            while j < end:
                merged[k] = numbers[j]
                j += 1
                k += 1
        for k in range(n):  # the round's runs, twice as long, copied back
            numbers[k] = merged[k]
        width *= 2
    return numbers


def cheapest(n):
    """The numbers n down to 1, back to front: every merge compares only its right run."""
    return list(range(n, 0, -1))


def count(row):
    """How many comparisons merge sort makes on this row."""
    Counted.comparisons = 0
    merge_sort([Counted(x) for x in row])
    return Counted.comparisons


if __name__ == "__main__":
    random.seed(1)
    print(f"{'n':>6} {'back to front':>14} {'in order':>10} {'shuffled':>10}")
    for n in [10, 100, 1000]:
        shuffles = []
        for _ in range(20):
            row = list(range(1, n + 1))
            random.shuffle(row)
            shuffles.append(count(row))
        in_order = count(list(range(1, n + 1)))
        print(f"{n:>6} {count(cheapest(n)):>14} {in_order:>10} {sum(shuffles) / 20:>10.1f}")

extra memory, the places the sort holds beyond the row itself, ten times more at each mark up

slope 1102104106101102103104105106107slope 1101102103104105106107101102103104105106107slope 1101102103104105106107101102103104105106107

nn, how many numbers are in the row, ten times more at each mark to the right

  • every row, whatever its ordersolid where measured by running it; dashed where its formula carries it on to ten millionslope 1: ten times n, 10 times the room

best, worst and average

Every row of 8 places 24, whatever its order; only the comparisons change. By the page on the sorting floor, every sort that only compares, with no random choices, has dearest rows whose cost grows at least as fast as n log⁡2 nn \,\log_2\, n. Merge sort's grow just that fast.

A case is one kind of input, the thing the method is given, such as a row back to front, whatever its length. A bound says how fast that case's cost grows as the input gets longer.

The counts are in the grid. A count is often the sum of pieces that grow at different speeds, and on long inputs the fastest-growing piece swamps the rest. For example, a count of half of n times n, less half of n: at 2,000 items, 2,000,000 less 1,000. So how a cost grows is what tells one method from another, and the bounds keep just that.

what each case costs, and how fast that cost grows; section 4 works out every formula in it
bestdifferent numbers back to front, a cheapest rowaverageshuffled, every order of different numbers as likelyworsta dearest row, where every merge compares all but its last number
comparisonsb1+b2+b4+…b_1 + b_2 + b_4 + \dots, each round's right run lengths added upbetween the best and the worstP−(n−1)P - (n - 1)
numbers placedPP, the same on every rowPP, the same on every rowPP, the same on every row
how the comparisons grow in each case
tight, Θ\ThetaΘ(n log⁡2 n)\Theta(n \,\log_2\, n)Θ(n log⁡2 n)\Theta(n \,\log_2\, n)Θ(n log⁡2 n)\Theta(n \,\log_2\, n)
ceiling, OOO(n log⁡2 n)O(n \,\log_2\, n)O(n log⁡2 n)O(n \,\log_2\, n)O(n log⁡2 n)O(n \,\log_2\, n)
floor, Ω\OmegaΩ(n log⁡2 n)\Omega(n \,\log_2\, n)Ω(n log⁡2 n)\Omega(n \,\log_2\, n)Ω(n log⁡2 n)\Omega(n \,\log_2\, n)

extra memory: a second row as long as the row

Extra memory is the room it needs on top of the input itself, while it runs.

row of 8numberscomparisonsplaced
back to front8 down to 11224
in order1 up to 81224
on averageall 40,320 ordersabout 15.7324
dearest1, 5, 3, 7, 2, 6, 4, 81724
8 numbers have 8 × 7 × ... × 1 = 40,320 orders, 8 choices for place 1, then 7, and on.
the row: 1, 2, 3, 4, 5, 6, 7, 8, 9111111111start22221round 1441round 281round 39round 42a run, its length insideno partner, carried downthe first runall in one runa merge in round 4, its numbers123456789123456789goes straight in, the other run used up
1 to 9 in order, as runs. The 9 waits alone until round 4.
row of 9round 1round 2round 3round 4in all
in order444820
back to front444113
In order, round 4 compares all 8 of its left run; back to front, only the 1.

where the formula comes from

Five ladders, one for each count in section 3, climb in small steps, each naming the line it uses.

How many numbers does merge sort place on nn numbers, and how does that grow?
  1. the move: the runs at the start of a round

    the line:
    a round with run length wfinds runs at places 1 to w,w+1 to 2w, and so on\begin{gathered} \text{a round with run length } w \\ \text{finds runs at places } 1 \text{ to } w, \\ w + 1 \text{ to } 2w, \text{ and so on} \end{gathered}
    the row: 31, 7, 49, 12, 56, 23, 421111111start2221round 143round 27round 32a run, its length insideno partner, carried downthe first runall in one run
    Runs of 1, then 2, 2, 2 and 1, then 4 and 3, then 7.

    why it is allowed: Round 1 starts from runs of 1, and merging in pairs from the left doubles them, as drawn. The last run may be shorter.

  2. the move: cut the round into stretches

    the line:
    the round merges stretchesof 2w places from the left:a left run of w or fewerand a right run of the rest\begin{gathered} \text{the round merges stretches} \\ \text{of } 2w \text{ places from the left:} \\ \text{a left run of } w \text{ or fewer} \\ \text{and a right run of the rest} \end{gathered}

    why it is allowed: By line 1, a merge takes 2w2w places. Only the last stretch can be short, and with ww or fewer it is a left run alone.

  3. the move: what each stretch places

    the line:
    a stretch with a right runplaces all its numbers;a last stretch with noright run places none\begin{gathered} \text{a stretch with a right run} \\ \text{places all its numbers;} \\ \text{a last stretch with no} \\ \text{right run places none} \end{gathered}
    run lengthstretcheswaitsplaced
    11 to 2, 3 to 4, 5 to 6, 7the 7th6
    21 to 4, 5 to 7none7
    41 to 7none7
    The rounds on 7 numbers, 6 + 7 + 7 = 20 placed.

    why it is allowed: A merge writes each of its numbers into the second row once. A left run alone waits; the Python copies it across, but no merge places it.

  4. the move: which rounds there are

    the line:
    the rounds have run lengths1,2,4 and on, each below n\begin{gathered} \text{the rounds have run lengths} \\ 1, 2, 4 \text{ and on, each below } n \end{gathered}

    why it is allowed: By line 1, places 1 to ww hold one run, so a second run, and so a round, exists exactly when ww is below nn. For 7 numbers, 1, 2 and 4, not 8.

  5. the move: add up the rounds

    the line:
    P=p1+p2+p4+…one term for eachrun length below n\begin{gathered} P = p_1 + p_2 + p_4 + \dots \\ \text{one term for each} \\ \text{run length below } n \end{gathered}

    why it is allowed: PP is the numbers placed in all, pwp_w those in the round with run length ww; one term a round, by line 4. For 7 numbers, 6 + 7 + 7 = 20.

  6. the move: the same on every row

    the line:
    P is the sameon every row\begin{gathered} P \text{ is the same} \\ \text{on every row} \end{gathered}

    why it is allowed: By lines 2 and 3, what a round places depends on nn and ww alone, never on the order. For 8 numbers, 24 on every order.

  7. the move: a ceiling for each term

    the line:
    each term is at most n\text{each term is at most } n

    why it is allowed: By line 3 a round places each number once at most.

  8. the move: add up the ceilings

    the line:
    P≤R×nP \le R \times n

    why it is allowed: RR counts the rounds. By lines 5 and 7, RR terms, each at most nn. For 7 numbers, 20 is at most 21.

  9. the move: number the rounds

    the line:
    round number k hasrun length 2k−1\begin{gathered} \text{round number } k \text{ has} \\ \text{run length } 2^{k - 1} \end{gathered}

    why it is allowed: Round 1 has run length 1, 2 to the power 0, and each round doubles it.

  10. the move: the last round's run length

    the line:
    2R−1≤n2^{R - 1} \le n

    why it is allowed: By line 9 the last round, round RR, has run length 2R−12^{R - 1}, below nn by line 4.

  11. the move: take the log to base 2 of both sides

    the line:
    R−1≤log⁡2 nR - 1 \le \log_2\, n
    numberlog× 2+ 11021428372.81
    7 lies between 4 and 8, its log between 2 and 3.

    why it is allowed: In line 10, the log of 2R−12^{R - 1} is R−1R - 1, and a bigger number has a bigger log. For 7 numbers, 2 is at most about 2.81.

  12. the move: add 1 to both sides

    the line:
    R≤log⁡2 n+1R \le \log_2\, n + 1

    why it is allowed: Line 11 plus 1.

  13. the move: multiply both sides by n

    the line:
    R×n≤n(log⁡2 n+1)R \times n \le n(\log_2\, n + 1)

    why it is allowed: Line 12 times nn, more than zero.

  14. the move: a simpler ceiling

    the line:
    P≤n(log⁡2 n+1)P \le n(\log_2\, n + 1)

    why it is allowed: Lines 8 and 13. For 7 numbers, 20 is at most about 26.65.

  15. the move: from 2 numbers on, the log is at least 1

    the line:
    1≤log⁡2 n for n≥21 \le \log_2\, n \text{ for } n \ge 2

    why it is allowed: The log of 2 is 1, and a bigger number has a bigger log.

  16. the move: add the log to both sides

    the line:
     log⁡2 n+1≤log⁡2 n+log⁡2 nfor n≥2\begin{gathered} \,\log_2\, n + 1 \le \log_2\, n + \log_2\, n \\ \text{for } n \ge 2 \end{gathered}

    why it is allowed: Line 15 plus log⁡2 n\log_2\, n.

  17. the move: add like to like

    the line:
    log⁡2 n+1≤2 log⁡2 n for n≥2\log_2\, n + 1 \le 2 \,\log_2\, n \text{ for } n \ge 2

    why it is allowed: In line 16, a log plus the same log is twice it.

  18. the move: multiply both sides by n again

    the line:
    n(log⁡2 n+1)≤2n log⁡2 nfor n≥2\begin{gathered} n(\log_2\, n + 1) \le 2n \,\log_2\, n \\ \text{for } n \ge 2 \end{gathered}

    why it is allowed: Line 17 times nn.

  19. the move: a simpler ceiling still

    the line:
    P≤2n log⁡2 n for n≥2P \le 2n \,\log_2\, n \text{ for } n \ge 2

    why it is allowed: Lines 14 and 18. For 7 numbers, 20 is at most about 39.30.

  20. the move: read it as a bound

    the line:
    P∈O(n log⁡2 n)P \in O(n \,\log_2\, n)

    why it is allowed: By line 19, at most 2 times n log⁡2 nn \,\log_2\, n.

  21. the move: the next run length is not below n

    the line:
    n≤2Rn \le 2^R

    why it is allowed: Now a floor. The next run length, 2R2^R by line 9, would make another round by line 4 if it were below nn. For 7 numbers, 7 is at most 8.

  22. the move: halve both sides of line 10

    the line:
    2R−2≤n22^{R - 2} \le \frac{n}{2}

    why it is allowed: Halving both sides keeps it true. For 7 numbers, 2 is at most 3.5.

  23. the move: what a round leaves out

    the line:
    a round places at leastn−w numbers\begin{gathered} \text{a round places at least} \\ n - w \text{ numbers} \end{gathered}

    why it is allowed: By line 3 a round leaves out at most a left run alone, ww places or fewer.

  24. the move: a round before the last has a short run length

    the line:
    a round before the last hasrun length at most n2\begin{gathered} \text{a round before the last has} \\ \text{run length at most } \frac{n}{2} \end{gathered}

    why it is allowed: By line 9 its run length is at most 2R−22^{R - 2}, so by line 22 at most half of nn.

  25. the move: so it places at least half the row

    the line:
    each round before the lastplaces at least n2\begin{gathered} \text{each round before the last} \\ \text{places at least } \frac{n}{2} \end{gathered}

    why it is allowed: By lines 23 and 24, nn less at most half of nn.

  26. the move: the last round places every number

    the line:
    the last round places all n\text{the last round places all } n

    why it is allowed: By lines 4 and 21 its run length is below nn and twice it is not, so by lines 2 and 3 it merges the whole row. For 7 numbers, 1 to 4 with 5 to 7.

  27. the move: add up the rounds again, from below

    the line:
    P≥(R−1)×n2+nfor n≥2\begin{gathered} P \ge (R - 1) \times \frac{n}{2} + n \\ \text{for } n \ge 2 \end{gathered}

    why it is allowed: Line 5, with lines 25 and 26; with 2 numbers no round comes before the last.

  28. the move: a simpler floor

    the line:
    P≥(R−1)×n2+n2for n≥2\begin{gathered} P \ge (R - 1) \times \frac{n}{2} + \frac{n}{2} \\ \text{for } n \ge 2 \end{gathered}

    why it is allowed: In line 27, nn is at least half of nn.

  29. the move: tidy the floor

    the line:
    P≥R×n2 for n≥2P \ge R \times \frac{n}{2} \text{ for } n \ge 2

    why it is allowed: In line 28, R−1R - 1 halves and one more make RR halves.

  30. the move: take the log to base 2 of both sides of line 21

    the line:
    log⁡2 n≤R\log_2\, n \le R

    why it is allowed: The log of 2R2^R is RR, and a bigger number has a bigger log.

  31. the move: multiply both sides by half of n

    the line:
    n2 log⁡2 n≤R×n2\frac{n}{2} \,\log_2\, n \le R \times \frac{n}{2}

    why it is allowed: Line 30 times half of nn.

  32. the move: a simpler floor still

    the line:
    P≥n2 log⁡2 n for n≥2P \ge \frac{n}{2} \,\log_2\, n \text{ for } n \ge 2

    why it is allowed: Lines 29 and 31. For 7 numbers, 20 is at least about 9.83.

  33. the move: read it as a bound

    the line:
    P∈Ω(n log⁡2 n)P \in \Omega(n \,\log_2\, n)

    why it is allowed: By line 32, at least half of n log⁡2 nn \,\log_2\, n.

  34. the move: a ceiling and a floor together

    the line:
    P∈Θ(n log⁡2 n)P \in \Theta(n \,\log_2\, n)

    why it is allowed: Lines 20 and 33 bound PP by the same growth. For 8 numbers, PP is 24, as is 8 times 3.

try it with a small nn: at n=6n = 6, line 5 gives P=16P = 16, which you can work out by hand

Which row costs the fewest comparisons, how many, and how does that grow?
  1. the move: a merge compares at least the run used up first

    the line:
    a merge compares at least asmany times as the run usedup first holds numbers\begin{gathered} \text{a merge compares at least as} \\ \text{many times as the run used} \\ \text{up first holds numbers} \end{gathered}

    why it is allowed: Each comparison places one number, and a merge compares only while both runs hold numbers. So each number of the run used up first took one. Merging 7, 42 with 18, 31, the 18 and 31 did.

  2. the move: the right run is never longer

    the line:
    in every merge, the right runis no longer than the left\begin{gathered} \text{in every merge, the right run} \\ \text{is no longer than the left} \end{gathered}

    why it is allowed: By the first ladder's line 2, a left run is a full ww, and the right run at most ww.

  3. the move: so a merge compares at least its right run's length

    the line:
    a merge compares at least asmany times as its right runholds numbers\begin{gathered} \text{a merge compares at least as} \\ \text{many times as its right run} \\ \text{holds numbers} \end{gathered}

    why it is allowed: By line 1. The run used up first is the right run, or the left, which holds at least as many by line 2.

  4. the move: on a row back to front, each run is below the runs to its left

    the line:
    on a row of different numbersback to front, each number ofa run is smaller than eachnumber of the runs to its left\begin{gathered} \text{on a row of different numbers} \\ \text{back to front, each number of} \\ \text{a run is smaller than each} \\ \text{number of the runs to its left} \end{gathered}
    the row: 6, 5, 4, 3, 2, 1111111start222round 142round 26round 32a run, its length insideno partner, carried downthe first runall in one runa merge in round 2, its numbers56343456goes straight in, the other run used up
    Round 2 merges 5, 6 with 3, 4 into 3, 4, 5, 6.
    after the round with run lengththe row
    none yet6, 5, 4, 3, 2, 1
    15, 6, 3, 4, 1, 2
    23, 4, 5, 6, 1, 2
    41, 2, 3, 4, 5, 6
    Every run stays below each run to its left.

    why it is allowed: Back to front, each number is below every number to its left. A merge only reorders its own stretch, so its run stays below the runs to its left.

  5. the move: so each merge compares exactly its right run's length

    the line:
    on a row of different numbersback to front, a merge comparesexactly as many times as itsright run holds numbers\begin{gathered} \text{on a row of different numbers} \\ \text{back to front, a merge compares} \\ \text{exactly as many times as its} \\ \text{right run holds numbers} \end{gathered}

    why it is allowed: By line 4 each comparison places a number of the right run, until it is used up. Then the left follows. Merging 5, 6 with 3, 4: 2 comparisons.

  6. the move: add up the merges

    the line:
    B=b1+b2+b4+…one term for eachrun length below n\begin{gathered} B = b_1 + b_2 + b_4 + \dots \\ \text{one term for each} \\ \text{run length below } n \end{gathered}

    why it is allowed: BB is the comparisons back to front, bwb_w what the right runs hold in the round with run length ww, by line 5. The rounds are the first ladder's line 4. For 7 numbers, 3 + 3 + 3 = 9.

  7. the move: no row costs fewer

    the line:
    every row costs at least B,so a row of different numbersback to front is a cheapest row\begin{gathered} \text{every row costs at least } B \text{,} \\ \text{so a row of different numbers} \\ \text{back to front is a cheapest row} \end{gathered}

    why it is allowed: By the first ladder's lines 2 and 4, every row of nn has the same merges, and by line 3 above each compares at least its right run. Equal numbers may cost more, as 3, 2, 2, 1 costs 5, not 4.

  8. the move: a right run is at most half its merge

    the line:
    each right run holds at mosthalf of the numbers itmerges with its left run\begin{gathered} \text{each right run holds at most} \\ \text{half of the numbers it} \\ \text{merges with its left run} \end{gathered}

    why it is allowed: By line 2.

  9. the move: add up the halves

    the line:
    B≤P2B \le \frac{P}{2}

    why it is allowed: Lines 6 and 8 above; the merges' numbers add up to PP, by the first ladder's line 5.

  10. the move: halve both sides of the first ladder's ceiling

    the line:
    P2≤n log⁡2 n for n≥2\frac{P}{2} \le n \,\log_2\, n \text{ for } n \ge 2

    why it is allowed: The first ladder's line 19, halved.

  11. the move: a simpler ceiling

    the line:
    B≤n log⁡2 n for n≥2B \le n \,\log_2\, n \text{ for } n \ge 2

    why it is allowed: Lines 9 and 10. For 7 numbers, 9 is at most about 19.65.

  12. the move: read it as a bound

    the line:
    B∈O(n log⁡2 n)B \in O(n \,\log_2\, n)

    why it is allowed: By line 11, at most n log⁡2 nn \,\log_2\, n itself.

  13. the move: the places the full stretches cover

    the line:
    a round’s full stretches covermore than n−2w places\begin{gathered} \text{a round's full stretches cover} \\ \text{more than } n - 2w \text{ places} \end{gathered}

    why it is allowed: Now a floor, adding only rounds with run length at most a quarter of nn. Only the last stretch can be short, so the full ones cover more than n−2wn - 2w. For 9 numbers and run length 2, 8 places, more than 5.

  14. the move: half of them are right runs

    the line:
    their right runs hold morethan half of (n−2w)\begin{gathered} \text{their right runs hold more} \\ \text{than half of } (n - 2w) \end{gathered}

    why it is allowed: A full stretch is a left run and a right run of ww each, by the first ladder's line 2. With line 13 above, the right runs hold more than half of n−2wn - 2w.

  15. the move: halve

    the line:
    half of (n−2w)is n2−w\begin{gathered} \text{half of } (n - 2w) \\ \text{is } \frac{n}{2} - w \end{gathered}

    why it is allowed: In line 14, half of 2w2w is ww.

  16. the move: the round's right runs

    the line:
    bw is more thann2−w\begin{gathered} b_w \text{ is more than} \\ \frac{n}{2} - w \end{gathered}

    why it is allowed: Lines 14 and 15, as bwb_w may also count a short last stretch's right run.

  17. the move: a round with a short run length

    the line:
    bw is at least n4when w is at most n4\begin{gathered} b_w \text{ is at least } \frac{n}{4} \\ \text{when } w \text{ is at most } \frac{n}{4} \end{gathered}
    run length4.5 less itthe right runs holdkept, run length at most 2.25
    13.54yes, kept
    22.54yes, kept
    40.54no
    8below 01no
    9 back to front; 4.5 is half of 9, 2.25 a quarter.

    why it is allowed: Then n2−w\frac{n}{2} - w is at least a quarter of nn, and bwb_w is more, by line 16. For 9 numbers and run length 2, 4 is at least 2.25.

  18. the move: name the longest short run length

    the line:
    let j be the largest whole numberwith 2j at most n4from 4 numbers on\begin{gathered} \text{let } j \text{ be the largest whole number} \\ \text{with } 2^j \text{ at most } \frac{n}{4} \\ \text{from 4 numbers on} \end{gathered}

    why it is allowed: The kept run lengths are powers of 2. From 4 numbers on a quarter of nn is at least 1, so jj exists. For 9 numbers, jj is 1, keeping 1 and 2.

  19. the move: count the rounds with a short run length

    the line:
    at least j+1 rounds haverun length at most n4from 4 numbers on\begin{gathered} \text{at least } j + 1 \text{ rounds have} \\ \text{run length at most } \frac{n}{4} \\ \text{from 4 numbers on} \end{gathered}

    why it is allowed: The j+1j + 1 run lengths 1, 2 and on up to 2j2^j are at most a quarter of nn, by line 18. So they are below nn, and rounds by the first ladder's line 4.

  20. the move: the next power of 2 is too big

    the line:
    2j+1 is morethan n4from 4 numbers on\begin{gathered} 2^{j + 1} \text{ is more} \\ \text{than } \frac{n}{4} \\ \text{from 4 numbers on} \end{gathered}

    why it is allowed: By line 18, jj is the largest.

  21. the move: take the log to base 2 of both sides

    the line:
    j+1 is morethan  log⁡2 n4from 4 numbers on\begin{gathered} j + 1 \text{ is more} \\ \text{than } \,\log_2\, \frac{n}{4} \\ \text{from 4 numbers on} \end{gathered}

    why it is allowed: In line 20, the log of 2j+12^{j + 1} is j+1j + 1, and a bigger number has a bigger log.

  22. the move: twice a half

    the line:
    log⁡2 n=1+log⁡2 n2 for n≥4\log_2\, n = 1 + \log_2\, \frac{n}{2} \text{ for } n \ge 4

    why it is allowed: Doubling adds 1 to a log, as question 1, line 2 of the page on growth and the growth ladder shows for any number from 1. From 4 numbers on, half of nn is at least 2.

  23. the move: twice a quarter

    the line:
    log⁡2 n2=1+log⁡2 n4 for n≥4\log_2\, \frac{n}{2} = 1 + \log_2\, \frac{n}{4} \text{ for } n \ge 4

    why it is allowed: Line 22's fact for a quarter of nn, at least 1 from 4 numbers on.

  24. the move: put line 23 into line 22, then take 2 from both sides

    the line:
    log⁡2 n4=log⁡2 n−2 for n≥4\log_2\, \frac{n}{4} = \log_2\, n - 2 \text{ for } n \ge 4

    why it is allowed: Line 23 in line 22 makes log⁡2 n\log_2\, n 2 more than the log of a quarter of nn. Take 2 from both sides. For 8 numbers, 1 is 3 less 2.

  25. the move: put lines 21 and 24 together

    the line:
    j+1≥log⁡2 n−2 for n≥4j + 1 \ge \log_2\, n - 2 \text{ for } n \ge 4

    why it is allowed: More than, so at least.

  26. the move: add up those rounds alone

    the line:
    B≥(j+1)×n4for n≥4\begin{gathered} B \ge (j + 1) \times \frac{n}{4} \\ \text{for } n \ge 4 \end{gathered}

    why it is allowed: No term of line 6 is below zero, so the short rounds alone give no more. Line 19 counts them, each at least a quarter of nn by line 17. For 8 numbers, 12 is at least 4.

  27. the move: multiply both sides of line 25 by a quarter of n

    the line:
    (j+1)×n4≥(log⁡2 n−2)×n4for n≥4\begin{gathered} (j + 1) \times \frac{n}{4} \ge (\log_2\, n - 2) \times \frac{n}{4} \\ \text{for } n \ge 4 \end{gathered}

    why it is allowed: A quarter of nn is more than zero.

  28. the move: put the two together

    the line:
    B≥(log⁡2 n−2)×n4for n≥4\begin{gathered} B \ge (\log_2\, n - 2) \times \frac{n}{4} \\ \text{for } n \ge 4 \end{gathered}

    why it is allowed: Lines 26 and 27. For 8 numbers, 12 is at least 2.

  29. the move: from 8 numbers on, the log is at least 3

    the line:
    3≤log⁡2 n for n≥83 \le \log_2\, n \text{ for } n \ge 8

    why it is allowed: The log of 8 is 3, and a bigger number has a bigger log.

  30. the move: multiply both sides by two thirds

    the line:
    2≤23 log⁡2 n for n≥82 \le \frac{2}{3} \,\log_2\, n \text{ for } n \ge 8

    why it is allowed: Line 29 times two thirds, as two thirds of 3 is the 2 of line 28.

  31. the move: take more away

    the line:
     log⁡2 n−2≥log⁡2 n−23 log⁡2 nfor n≥8\begin{gathered} \,\log_2\, n - 2 \ge \log_2\, n - \frac{2}{3} \,\log_2\, n \\ \text{for } n \ge 8 \end{gathered}

    why it is allowed: By line 30, two thirds of the log is at least 2, and taking more away leaves less.

  32. the move: tidy

    the line:
    log⁡2 n−2≥13 log⁡2 n for n≥8\log_2\, n - 2 \ge \frac{1}{3} \,\log_2\, n \text{ for } n \ge 8

    why it is allowed: In line 31, a whole log less two thirds of it is a third.

  33. the move: multiply both sides by a quarter of n

    the line:
    (log⁡2 n−2)×n4≥13 log⁡2 n×n4for n≥8\begin{gathered} (\log_2\, n - 2) \times \frac{n}{4} \ge \frac{1}{3} \,\log_2\, n \times \frac{n}{4} \\ \text{for } n \ge 8 \end{gathered}

    why it is allowed: Line 32 times a quarter of nn.

  34. the move: tidy

    the line:
    (log⁡2 n−2)×n4≥n log⁡2 n12for n≥8\begin{gathered} (\log_2\, n - 2) \times \frac{n}{4} \ge \frac{n \,\log_2\, n}{12} \\ \text{for } n \ge 8 \end{gathered}

    why it is allowed: In line 33, a third times a quarter is a twelfth.

  35. the move: a simpler floor

    the line:
    B≥n log⁡2 n12 for n≥8B \ge \frac{n \,\log_2\, n}{12} \text{ for } n \ge 8

    why it is allowed: Lines 28 and 34. For 8 numbers, 12 is at least 2.

  36. the move: read it as a bound

    the line:
    B∈Ω(n log⁡2 n)B \in \Omega(n \,\log_2\, n)

    why it is allowed: By line 35, at least a twelfth of n log⁡2 nn \,\log_2\, n from 8 numbers on.

  37. the move: a ceiling and a floor together

    the line:
    B∈Θ(n log⁡2 n)B \in \Theta(n \,\log_2\, n)

    why it is allowed: Lines 12 and 36 bound BB by the same growth. For 8 numbers, BB is 12.

try it with a small nn: at n=8n = 8, line 6 gives B=12B = 12, which you can work out by hand

What is the most a row of nn can cost, which row costs it, and how does that grow?
  1. the move: a merge places its last number with no comparison

    the line:
    merging runs of x and ynumbers compares atmost x+y−1 times\begin{gathered} \text{merging runs of } x \text{ and } y \\ \text{numbers compares at} \\ \text{most } x + y - 1 \text{ times} \end{gathered}
    the row: 31, 7, 42, 181111start22round 14round 22a run, its length insidethe first runall in one runa merge in round 2, its numbers73118427183142goes straight in, the other run used up
    Round 2 merges 7, 31 with 18, 42 into 7, 18, 31, 42.

    why it is allowed: xx and yy are the runs' lengths. Each comparison places one number. The comparison that uses up one run leaves a number in the other, which follows with none. Merging 7, 31 with 18, 42: 3 comparisons.

  2. the move: count the merges

    the line:
    a row of n numberstakes n−1 merges\begin{gathered} \text{a row of } n \text{ numbers} \\ \text{takes } n - 1 \text{ merges} \end{gathered}

    why it is allowed: Each merge turns two runs into one, and a run that waits stays one. So nn runs need n−1n - 1 merges. For 8 numbers, 4 + 2 + 1.

  3. the move: add up the merges

    the line:
    on any row, the comparisonsare at most P−(n−1)\begin{gathered} \text{on any row, the comparisons} \\ \text{are at most } P - (n - 1) \end{gathered}

    why it is allowed: Line 1 for each merge, the numbers adding up to PP by the first ladder's line 5, and line 2 above counting the merges. For 8 numbers, 24 less 7, 17.

  4. the move: when a merge runs to its last pair

    the line:
    merging different numbers,a merge comparesx+y−1 times whenits largest number andits next largest standin different runs\begin{gathered} \text{merging different numbers,} \\ \text{a merge compares} \\ x + y - 1 \text{ times when} \\ \text{its largest number and} \\ \text{its next largest stand} \\ \text{in different runs} \end{gathered}

    why it is allowed: The next largest ends its run, so that run lasts until all but the largest are placed. The largest waits in the other run all along, so each placing took a comparison. Merging 7, 31 with 18, 42: 3.

  5. the move: the last merge's two parts

    the line:
    the last merge joins places1 to 2R−1 with the rest\begin{gathered} \text{the last merge joins places} \\ 1 \text{ to } 2^{R - 1} \text{ with the rest} \end{gathered}

    why it is allowed: By the first ladder's lines 9, 4 and 21, the last run length, 2R−12^{R - 1}, is below nn and twice it is not. So by the first ladder's line 2 the last stretch is the whole row. For 8 numbers, 1 to 4 and 5 to 8.

  6. the move: earlier merges stay inside one part

    the line:
    every earlier merge joinsnumbers of one part only\begin{gathered} \text{every earlier merge joins} \\ \text{numbers of one part only} \end{gathered}

    why it is allowed: By the first ladder's line 9, an earlier stretch, 2w2w places, is a power of 2 up to the left part's 2R−12^{R - 1}. So these stretches fill places 1 to 2R−12^{R - 1} exactly, and none crosses. For 7 numbers, 1 to 4 holds two stretches of 2, then one of 4.

  7. the move: each part is merged as a row of its own

    the line:
    each part is mergedjust as a row of itsown would be\begin{gathered} \text{each part is merged} \\ \text{just as a row of its} \\ \text{own would be} \end{gathered}

    why it is allowed: By line 6 each part is cut as a row of its own. Its own rounds have run lengths 1, 2, 4 and on, below its length, by the first ladder's line 4. Each part holds at most 2R−12^{R - 1}, by line 5, so these come before the last round, by the first ladder's line 9. In other rounds a short part waits, as the 9th of 9 does.

  8. the move: build a row where every merge runs to its last pair

    the line:
    deal the numbers fromthe largest down, to theright part and to the leftpart in turn; then thesame again inside each part\begin{gathered} \text{deal the numbers from} \\ \text{the largest down, to the} \\ \text{right part and to the left} \\ \text{part in turn; then the} \\ \text{same again inside each part} \end{gathered}
    the row: 1, 5, 3, 7, 2, 6, 4, 811111111start2222round 144round 28round 32a run, its length insidethe first runall in one runa merge in round 3, its numbers1357246812345678goes straight in, the other run used up
    Round 3 merges 1, 3, 5, 7 with 2, 4, 6, 8, from each run in turn.
    the numbersthe left part getsthe right part gets
    1 to 87, 5, 3, 18, 6, 4, 2
    7, 5, 3, 15, 17, 3
    8, 6, 4, 26, 28, 4
    5, 115
    7, 337
    6, 226
    8, 448
    Largest first, right first; the bottom four lines give 1, 5, 3, 7, 2, 6, 4, 8.

    why it is allowed: By line 5 the right part is never the longer; once it is full, the rest go left. The two largest stand apart, so by line 4 the last merge makes x+y−1x + y - 1. Lines 6 and 7 let each part be dealt the same way.

  9. the move: add up that row's merges

    the line:
    the row of line 8 costsexactly P−(n−1)\begin{gathered} \text{the row of line 8 costs} \\ \text{exactly } P - (n - 1) \end{gathered}

    why it is allowed: Line 8 in every merge, added up as in line 3.

  10. the move: the most any row costs

    the line:
    W=P−(n−1)W = P - (n - 1)

    why it is allowed: WW is the comparisons on a dearest row. Line 3 caps every row, and the row of line 9 reaches the cap.

  11. the move: a ceiling

    the line:
    W≤PW \le P

    why it is allowed: In line 10, n−1n - 1 is not below 0.

  12. the move: a simpler ceiling

    the line:
    W≤2n log⁡2 n for n≥2W \le 2n \,\log_2\, n \text{ for } n \ge 2

    why it is allowed: Line 11 above and the first ladder's line 19.

  13. the move: read it as a bound

    the line:
    W∈O(n log⁡2 n)W \in O(n \,\log_2\, n)

    why it is allowed: By line 12, at most 2 times n log⁡2 nn \,\log_2\, n.

  14. the move: a floor

    the line:
    W≥n2 log⁡2 n−(n−1)for n≥2\begin{gathered} W \ge \frac{n}{2} \,\log_2\, n - (n - 1) \\ \text{for } n \ge 2 \end{gathered}

    why it is allowed: Now a floor, putting the first ladder's line 32 into line 10 above.

  15. the move: take away a little more

    the line:
    W≥n2 log⁡2 n−n for n≥2W \ge \frac{n}{2} \,\log_2\, n - n \text{ for } n \ge 2

    why it is allowed: In line 14, nn is more than n−1n - 1.

  16. the move: from 8 numbers on, the log is at least 3

    the line:
    3≤log⁡2 n for n≥83 \le \log_2\, n \text{ for } n \ge 8

    why it is allowed: The log of 8 is 3, and a bigger number has a bigger log.

  17. the move: multiply both sides by a third of n

    the line:
    n≤n3 log⁡2 n for n≥8n \le \frac{n}{3} \,\log_2\, n \text{ for } n \ge 8

    why it is allowed: Line 16 times a third of nn, as a third of nn times 3 is nn.

  18. the move: take more away still

    the line:
    n2 log⁡2 n−n≥n2 log⁡2 n−n3 log⁡2 nfor n≥8\begin{gathered} \frac{n}{2} \,\log_2\, n - n \ge \frac{n}{2} \,\log_2\, n - \frac{n}{3} \,\log_2\, n \\ \text{for } n \ge 8 \end{gathered}

    why it is allowed: By line 17 the right side takes away at least nn.

  19. the move: put the two together

    the line:
    W≥n2 log⁡2 n−n3 log⁡2 nfor n≥8\begin{gathered} W \ge \frac{n}{2} \,\log_2\, n - \frac{n}{3} \,\log_2\, n \\ \text{for } n \ge 8 \end{gathered}

    why it is allowed: Lines 15 and 18.

  20. the move: tidy the floor

    the line:
    W≥n6 log⁡2 n for n≥8W \ge \frac{n}{6} \,\log_2\, n \text{ for } n \ge 8

    why it is allowed: In line 19, a half less a third is a sixth. For 8 numbers, 17 is at least 4.

  21. the move: read it as a bound

    the line:
    W∈Ω(n log⁡2 n)W \in \Omega(n \,\log_2\, n)

    why it is allowed: By line 20, at least a sixth of n log⁡2 nn \,\log_2\, n from 8 numbers on.

  22. the move: a ceiling and a floor together

    the line:
    W∈Θ(n log⁡2 n)W \in \Theta(n \,\log_2\, n)

    why it is allowed: Lines 13 and 21 bound WW by the same growth.

try it with a small nn: at n=8n = 8, line 10 gives W=17W = 17, which you can work out by hand

Between what does a shuffle's average lie, and how does it grow?
  1. the move: at least the cheapest row

    the line:
    A≥BA \ge B
    rowcheapeston averagedearest
    8 numbers12about 15.73, every order17
    1,000 numbers4,932about 8,720, 20 shuffles8,985
    The average lies between, nearer the dearest.

    why it is allowed: AA is the average over every order of nn different numbers, estimated in section 2 from 20 shuffles. No row costs less than BB, by the second ladder's line 7, so neither does an average.

  2. the move: the second ladder's floor

    the line:
    A≥n log⁡2 n12 for n≥8A \ge \frac{n \,\log_2\, n}{12} \text{ for } n \ge 8

    why it is allowed: The second ladder's line 35, with line 1 above.

  3. the move: read it as a bound

    the line:
    A∈Ω(n log⁡2 n)A \in \Omega(n \,\log_2\, n)

    why it is allowed: By line 2.

  4. the move: at most the dearest row

    the line:
    A≤WA \le W

    why it is allowed: By the third ladder's lines 3 and 10, no row costs more than WW, so neither does an average.

  5. the move: the third ladder's ceiling

    the line:
    A≤2n log⁡2 n for n≥2A \le 2n \,\log_2\, n \text{ for } n \ge 2

    why it is allowed: The third ladder's line 12, with line 4 above.

  6. the move: read it as a bound

    the line:
    A∈O(n log⁡2 n)A \in O(n \,\log_2\, n)

    why it is allowed: By line 5.

  7. the move: a ceiling and a floor together

    the line:
    A∈Θ(n log⁡2 n)A \in \Theta(n \,\log_2\, n)

    why it is allowed: Lines 3 and 6 bound AA by the same growth, with no formula needed.

try it on small rows: over every order of 8 numbers, the average AA is about 15.73

How much extra memory does merge sort hold, and how does it grow?
  1. the move: the second row

    the line:
    the merges write intoone second row of n places\begin{gathered} \text{the merges write into} \\ \text{one second row of } n \text{ places} \end{gathered}
    fronts comparedplacedthe second row so far
    7 and 1877
    42 and 18187, 18
    42 and 31317, 18, 31
    none, the right run is used up427, 18, 31, 42
    Merging 7, 42 with 18, 31 into the second row.

    why it is allowed: Each round writes its runs into a second row of nn places, then copies them back, so the next round uses it again.

  2. the move: count the places

    the line:
    M=n for n≥2M = n \text{ for } n \ge 2

    why it is allowed: By line 1, MM is the second row's nn places, whatever the order. The few spare places, such as the run length, do not grow.

  3. the move: a ceiling

    the line:
    M≤n for n≥2M \le n \text{ for } n \ge 2

    why it is allowed: By line 2.

  4. the move: a floor

    the line:
    M≥n for n≥2M \ge n \text{ for } n \ge 2

    why it is allowed: By line 2.

  5. the move: a ceiling and a floor together

    the line:
    M∈Θ(n)M \in \Theta(n)

    why it is allowed: Lines 3 and 4.

try it with a small nn: at n=6n = 6, line 2 gives M=6M = 6, which you can work out by hand

count it yourself

Follow every step on 6 numbers.

45, 13, 62, 6, 33, 28, every step written down
stepthe rowwhat happenscomparisonsnumbers placed
145, 13, 62, 6, 33, 28There are 6 numbers in a row. Each one on its own is a run in order.45, 13, 62, 6, 33, 2800
245, 13, 62, 6, 33, 28Merge neighbouring runs of 1 number into runs of up to 2.45, 13, 62, 6, 33, 2800
345, 13, 62, 6, 33, 28Merge the run that starts at place 1 with the one that starts at place 2.45, 13, 62, 6, 33, 2800
445, 13, 62, 6, 33, 2813 is smaller than 45, so 13 goes next.45, 13, 62, 6, 33, 2810
513, 45, 62, 6, 33, 2813 moves in front of 45, and the left run moves one place right to make room.13, 45, 62, 6, 33, 2811
613, 45, 62, 6, 33, 28One run is used up, so the 1 number left in the other follows as it stands.13, 45, 62, 6, 33, 2812
713, 45, 62, 6, 33, 28Merge the run that starts at place 3 with the one that starts at place 4.13, 45, 62, 6, 33, 2812
813, 45, 62, 6, 33, 286 is smaller than 62, so 6 goes next.13, 45, 62, 6, 33, 2822
913, 45, 6, 62, 33, 286 moves in front of 62, and the left run moves one place right to make room.13, 45, 6, 62, 33, 2823
1013, 45, 6, 62, 33, 28One run is used up, so the 1 number left in the other follows as it stands.13, 45, 6, 62, 33, 2824
1113, 45, 6, 62, 33, 28Merge the run that starts at place 5 with the one that starts at place 6.13, 45, 6, 62, 33, 2824
1213, 45, 6, 62, 33, 2828 is smaller than 33, so 28 goes next.13, 45, 6, 62, 33, 2834
1313, 45, 6, 62, 28, 3328 moves in front of 33, and the left run moves one place right to make room.13, 45, 6, 62, 28, 3335
1413, 45, 6, 62, 28, 33One run is used up, so the 1 number left in the other follows as it stands.13, 45, 6, 62, 28, 3336
1513, 45, 6, 62, 28, 33Merge neighbouring runs of up to 2 numbers into runs of up to 4.13, 45, 6, 62, 28, 3336
1613, 45, 6, 62, 28, 33Merge the run that starts at place 1 with the one that starts at place 3.13, 45, 6, 62, 28, 3336
1713, 45, 6, 62, 28, 336 is smaller than 13, so 6 goes next.13, 45, 6, 62, 28, 3346
186, 13, 45, 62, 28, 336 moves in front of 13, and the left run moves one place right to make room.6, 13, 45, 62, 28, 3347
196, 13, 45, 62, 28, 3313 is not bigger than 62, so 13 goes next, where it already stands.6, 13, 45, 62, 28, 3358
206, 13, 45, 62, 28, 3345 is not bigger than 62, so 45 goes next, where it already stands.6, 13, 45, 62, 28, 3369
216, 13, 45, 62, 28, 33One run is used up, so the 1 number left in the other follows as it stands.6, 13, 45, 62, 28, 33610
226, 13, 45, 62, 28, 33The run that starts at place 5 has no partner this round, so it waits.6, 13, 45, 62, 28, 33610
236, 13, 45, 62, 28, 33Merge neighbouring runs of up to 4 numbers into runs of up to 6.6, 13, 45, 62, 28, 33610
246, 13, 45, 62, 28, 33Merge the run that starts at place 1 with the one that starts at place 5.6, 13, 45, 62, 28, 33610
256, 13, 45, 62, 28, 336 is not bigger than 28, so 6 goes next, where it already stands.6, 13, 45, 62, 28, 33711
266, 13, 45, 62, 28, 3313 is not bigger than 28, so 13 goes next, where it already stands.6, 13, 45, 62, 28, 33812
276, 13, 45, 62, 28, 3328 is smaller than 45, so 28 goes next.6, 13, 45, 62, 28, 33912
286, 13, 28, 45, 62, 3328 moves in front of 45, and the left run moves one place right to make room.6, 13, 28, 45, 62, 33913
296, 13, 28, 45, 62, 3333 is smaller than 45, so 33 goes next.6, 13, 28, 45, 62, 331013
306, 13, 28, 33, 45, 6233 moves in front of 45, and the left run moves one place right to make room.6, 13, 28, 33, 45, 621014
316, 13, 28, 33, 45, 62One run is used up, so the 2 numbers left in the other follow as they stand.6, 13, 28, 33, 45, 621016
326, 13, 28, 33, 45, 62In order, after 10 comparisons, with 16 numbers placed into merged runs.6, 13, 28, 33, 45, 621016

In all, 16 numbers placed. The formula from section 4, p1+p2+p4+…p_1 + p_2 + p_4 + \dots, gives P=16P = 16 at n=6n = 6: the same.

where you meet it

Merge sort keeps equal items in order, at the price of a second row.

  • the C++ library's stable sort

    The GNU C++ library's std::stable_sort keeps equal items in order. With room for half the row, it sorts each half bottom up, from groups of 7 sorted by insertion sort, then merges the halves.

    source: the GNU C++ library's stl_algo.h in GCC 15, its __stable_sort, __merge_sort_with_buffer and __chunk_insertion_sort, chunk size 7

  • Timsort, in Python and Java

    Python's list sort, and Java's for things other than plain numbers, use Timsort. It is a merge sort that starts from runs already in the row. A row in order is one run.

    source: the books' volume one, chapter 10; Python 3.14's list.sort, run for this page; OpenJDK 25's java.util.ComparableTimSort and java.util.TimSort

  • sorting a file too big for memory

    A merge reads each run from front to back, so runs can wait in files on a disk. The GNU sort command sorts big files this way, merging up to 16 at once by default.

    source: the GNU coreutils 9.7 manual, the sort command's option batch-size

what is used instead

When room is short and equal items may swap, a sort needing less room is used instead. The GNU C++ library's std::sort is one; it splits like quick sort.

how it compares

Merge sort beside the other sorts, on one plot and in one table.

comparisons on a shuffled row, on the log-log scales of section 2, one line for each way whose page is written
102104106108101010121014101102103104105106107bubble sortcocktail shaker sortinsertion sortselection sortshell sortquick sortrandomised quick sortheap sortmerge sort10110210310410510610710810910101011101210131014101102103104105106107bubble sortcocktail shaker sortinsertion sortselection sortshell sortquick sortrandomised quick sortheap sortmerge sort
  • bubble sort
  • cocktail shaker sort
  • insertion sort
  • selection sort
  • shell sort
  • quick sort
  • randomised quick sort
  • merge sort
  • heap sort
put a row in order: each way side by side
waybestaverageworstextra memorykeeps equal items in orderworks in placereach for it when
bubble sortΘ(n)\Theta(n)Θ(n2)\Theta(n^2)Θ(n2)\Theta(n^2)a few spare places (the walk number, the pair's place, whether the walk swapped, room for a number while two swap), the same however long the rowyesyesyou are learning how sorting works; for real work, insertion sort, which on every order of up to 8 different numbers makes no more comparisons, counted order by order
cocktail shaker sortΘ(n)\Theta(n)Θ(n2)\Theta(n^2)Θ(n2)\Theta(n^2)a few spare places, the same however long the rowyesyesyou are learning how sorting works; for real work, insertion sort
insertion sortΘ(n)\Theta(n)Θ(n2)\Theta(n^2)Θ(n2)\Theta(n^2)room for a few numbers (the number being placed, where its slide has reached, which number is next), the same however long the rowyesyesthe row is short, a few dozen numbers, or nearly in order
selection sortΘ(n2)\Theta(n^2)Θ(n2)\Theta(n^2)Θ(n2)\Theta(n^2)room for a few numbers (the place being filled, where the smallest so far stands, the number looked at, one held during a swap), the same however long the rownoyesmoving a number costs far more than comparing two, and the row is short
shell sortΘ(n log⁡2 n)\Theta(n \,\log_2\, n)not known; between Ω(n log⁡2 n)\Omega(n \,\log_2\, n) and O(n2)O(n^2)not worked out here; between Ω(n log⁡2 n)\Omega(n \,\log_2\, n) and O(n2)O(n^2)a few spare places (the gap, the number picked up, its place), the same however long the rownoyesyou want a few lines of code and no room beyond the row. On this site's shuffles of 200 to 10,000 numbers it averaged under a fifth of insertion sort's comparisons
quick sortΘ(n log⁡2 n)\Theta(n \,\log_2\, n)Θ(n log⁡2 n)\Theta(n \,\log_2\, n)Θ(n2)\Theta(n^2)a list of the parts still to sort, two memory places each. That is two places for each number on a row in order, and far fewer on a shuffle, about 51 for 100,000 numbers. So this plain version does not work in place, as its spare room grows with the rownonoyou want a fast sort on shuffled rows with no second row, and equal items need not keep their order; use a version with a random or middle pivot
randomised quick sortat most O(n log⁡2 n)O(n \,\log_2\, n), as every row of different numbers averages that over the picks; a row with equal numbers can cost a little lessΘ(n log⁡2 n)\Theta(n \,\log_2\, n)Θ(n2)\Theta(n^2), a row of equal numbers, whatever the picks; no run costs more, since a pair meets at most oncea list of the parts waiting to be sorted, each kept as its first and last place. On average far shorter than the row, about 66 places for a million numbers. Unlucky picks can make it grow with the rownonoyou want quick sort without a dear row in order, and equal items need not keep their order
merge sortΘ(n log⁡2 n)\Theta(n \,\log_2\, n)Θ(n log⁡2 n)\Theta(n \,\log_2\, n)Θ(n log⁡2 n)\Theta(n \,\log_2\, n)a second row as long as the rowyesnoyou need comparisons growing no faster than n log⁡2 nn \,\log_2\, n on every row, equal items kept in order, or a file too big for memory sorted
heap sortΘ(n)\Theta(n), every number the sameΘ(n log⁡2 n)\Theta(n \,\log_2\, n), shuffled; measured, no formula worked out hereΘ(n log⁡2 n)\Theta(n \,\log_2\, n), the dearest row; this page finds it only for short rows, by trying every ordera few places, however long the rownoyesyou need a sort with no slow row and no second row, and equal items need not keep their order
counting sortΘ(n)\Theta(n) steps, every row alikeΘ(n)\Theta(n) stepsΘ(n)\Theta(n) steps, every row alikea second row of n places and 10 talliesyesnothe numbers are small whole numbers, such as ratings from 0 to 9, and equal ones must keep their order
radix sortΘ(n)\Theta(n) placings, every number below 10Θ(n)\Theta(n) placings, between the best and the worst, as every order costs the sameΘ(n)\Theta(n) placings, three passes for numbers up to 999a second row of n places and 10 talliesyesnomany whole numbers with few digits, such as numbers from 0 to 999
extra memory:
the room it needs on top of the input itself, while it runs.
keeps equal items in order:
people sorted by age keep the order they arrived in within each age; in general, two items equal in what is being sorted come out in the order they went in.
works in place:
it rearranges the input where it stands, with only a few spare places, rather than building a copy; a different sense from a number being in place, in its final position.

race them on one row of your own