Skip to content

Heap sort

ordering

Level 3 of 3

how it works

The idea in a few sentences and three pictures, then one row sorted step by step.

Heap sort reads the row as a tree: the number in place pp has its children in places 2p2p and 2p+12p + 1. Take the row 42, 7, 31, 18, 56, 23, 12, the first picture. First heap sort builds a heap: it sifts places 3, 2 and 1, in that order. The row becomes 56, 42, 31, 18, 7, 23, 12, the second picture: 56 sits over 42 and 31, and 42 over 18 and 7. No number sits under a smaller one, and that is a heap. Then heap sort swaps the top, the biggest still in the heap, with the last number of the heap, where it stays. The heap is one smaller, the new top sifts down, and this repeats until one number is left.

depth012427311856231242172313184565236127012
The row 42, 7, 31, 18, 56, 23, 12 as a tree above the same row. Place 1 holds 42; its children, places 2 and 3, hold 7 and 31.
564231187231256142231318475236127
After building. Place 3 sifted first, and 31 stayed. Then 7 at place 2 dropped below 56. Then 42 at place 1 dropped below 56. Now no number sits under a smaller one.
the row42, 7, 31, 18, 56, 23, 12
after top 112, 42, 31, 18, 7, 23, 56
after top 223, 18, 31, 12, 7, 42, 56
after top 37, 18, 23, 12, 31, 42, 56
after top 412, 18, 7, 23, 31, 42, 56
after top 57, 12, 18, 23, 31, 42, 56
after top 67, 12, 18, 23, 31, 42, 56
The row after each swap of the top to the end. The biggest still in the heap joins the end each time, so the end grows in order, 56, then 42, 56, and on.
A short shuffle: 7 moments of its 53 steps, the steps between them left for the watch page
  1. step 2 of 53

    427311856231214227331418556623712

    Sift 31 down: while a child is bigger, swap it with its bigger child.

    what it remembers to know where it is
    numbers in the heap
    7
    number sifting down
    31
    at place
    3

    watch from here

  2. step 9 of 53

    425631187231214225633141857623712

    Swap 7 down with its bigger child, 56.

    what it remembers to know where it is
    numbers in the heap
    7
    number sifting down
    7
    at place
    2

    watch from here

  3. step 14 of 53

    564231187231215624233141857623712

    Swap 42 down with its bigger child, 56.

    what it remembers to know where it is
    numbers in the heap
    7
    number sifting down
    42
    at place
    1

    watch from here

  4. step 18 of 53

    564231187231215624233141857623712

    Every number is now at least as big as its children, so the biggest, 56, is at the top.

    what it remembers to know where it is
    numbers in the heap
    7
    number sifting down
    not yet
    at place
    not yet

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

    watch from here

  5. step 19 of 53

    124231187235611224233141857623756

    Swap the top, 56, the biggest left, to the end of the heap, where it stays for good.

    what it remembers to know where it is
    numbers in the heap
    6
    number sifting down
    not yet
    at place
    not yet

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

    watch from here

  6. step 26 of 53

    421831127235614221833141257623756

    Swap 12 down with its bigger child, 18.

    what it remembers to know where it is
    numbers in the heap
    6
    number sifting down
    12
    at place
    2

    watch from here

  7. step 53 of 53

    712182331425617212318423531642756

    In order, after 19 comparisons and 14 swaps.

    what it remembers to know where it is
    numbers in the heap
    0
    number sifting down
    not yet
    at place
    not yet

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

    watch from here

the steps, in plain words
  1. read the row as a tree: a number's children sit at twice its place and one morePython line 13
  2. for each parent, from the last back to the first, sift it downPython lines 26 and 27
  3. the biggest is now at the top; repeat until one number is left in the heapPython line 28
  4. swap the top with the last number of the heap, where it staysPython line 29
  5. sift the new top downPython line 30
  6. sifting down: while a child is bigger, swap the number with its bigger childPython lines 12, 16, 17, 18, 19, 20, 22 and 23
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 heap_sort(numbers):
    """Put a list of numbers in order, smallest first, in the list itself.

    Read the list as a tree, and build a heap: no number may sit under a
    smaller one. Then swap the top, the biggest still in the heap, with the
    heap's last number, where it stays, and let the new top sift down. Python
    counts places from 0, so the children of place p are 2p + 1 and 2p + 2.
    """

    def sift(place, size):
        """Sift the number at place down the heap of the first size numbers."""
        while True:
            first = 2 * place + 1  # its first child; the second is next
            if first >= size:  # no child in the heap: it stops
                return
            big = place  # the biggest so far: the number itself
            for child in (first, first + 1):  # each child in the heap
                if child < size and numbers[child] > numbers[big]:
                    big = child
            if big == place:  # no child is bigger: it stops
                return
            numbers[place], numbers[big] = numbers[big], numbers[place]
            place = big  # one level down

    size = len(numbers)
    for place in range(size // 2 - 1, -1, -1):  # each parent, last first
        sift(place, size)
    for end in range(size - 1, 0, -1):  # until one number is left
        numbers[0], numbers[end] = numbers[end], numbers[0]  # top to the end
        sift(0, end)  # the heap is one smaller: sift the new top down
    return numbers

how it scales

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

Each step across or up is ten times the one before, a log-log plot. The line for equal numbers, 3n−63n - 6, climbs about one step up for each step across from 100 numbers on: ten times the numbers, about ten times the comparisons. From 10 to 100 it is more, 24 to 294. The shuffled points climb more than one step each time, by less as they grow. Each tenfold step in numbers multiplies their comparisons by about 27, 16, 14, 13 and 12, from 10 numbers up to a million.

comparisons, ten times more at each mark up

slope 1102104106108101102103104105106107slope 1101102103104105106107108101102103104105106107slope 1101102103104105106107108101102103104105106107

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

  • shuffled, the average over every order of different numbers, each order as likelypoints only, each measured by a real run, since no single formula for the comparisons of this row is worked out here
  • every number the same, the cheapest rowsolid where measured by running it; dashed where its formula carries it on to ten millionslope 1: ten times n, 10 times the work
what a cheapest row costs, at a billion comparisons a second
nncomparisonstime
1,0002,994about 3 microseconds
100,000299,994about 300 microseconds
10,000,00029,999,994about 30 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 heap 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 of numbers all the same, the cheapest row, and the average over 20
shuffles. The counts are the same on any computer; only the time differs.
"""
import random


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

    comparisons = 0

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

    def __gt__(self, other):
        Counted.comparisons += 1
        return self.value > other.value


def heap_sort(numbers):
    """Put a list of numbers in order, smallest first, in the list itself.

    Read the list as a tree, and build a heap: no number may sit under a
    smaller one. Then swap the top, the biggest still in the heap, with the
    heap's last number, where it stays, and let the new top sift down. Python
    counts places from 0, so the children of place p are 2p + 1 and 2p + 2.
    """

    def sift(place, size):
        """Sift the number at place down the heap of the first size numbers."""
        while True:
            first = 2 * place + 1  # its first child; the second is next
            if first >= size:  # no child in the heap: it stops
                return
            big = place  # the biggest so far: the number itself
            for child in (first, first + 1):  # each child in the heap
                if child < size and numbers[child] > numbers[big]:
                    big = child
            if big == place:  # no child is bigger: it stops
                return
            numbers[place], numbers[big] = numbers[big], numbers[place]
            place = big  # one level down

    size = len(numbers)
    for place in range(size // 2 - 1, -1, -1):  # each parent, last first
        sift(place, size)
    for end in range(size - 1, 0, -1):  # until one number is left
        numbers[0], numbers[end] = numbers[end], numbers[0]  # top to the end
        sift(0, end)  # the heap is one smaller: sift the new top down
    return numbers


def cheapest(n):
    """n numbers all the same: every sift stops at once."""
    return [1] * n


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


if __name__ == "__main__":
    random.seed(1)
    print(f"{'n':>6} {'all the same':>13} {'shuffled':>10}")
    for n in [10, 100, 1000, 10000]:
        shuffles = []
        for _ in range(20):
            row = list(range(1, n + 1))
            random.shuffle(row)
            shuffles.append(count(row))
        print(f"{n:>6} {count(cheapest(n)):>13} {sum(shuffles) / 20:>10.1f}")

best, worst and average

The row decides the cost. Equal numbers are the cheapest: every sift stops at once. From 4 numbers on, shuffled rows cost more on average. This page works out no formula for their average, but section 4 finds how it grows. There is no worst column: this page names no dearest row. The table finds the dearest order of short rows by trying every order, and section 4 bounds its cost for every length.

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
bestevery number the same, the cheapest rowaverageshuffled, the average over every order of different numbers, each order as likely
comparisons3n−63n - 6, from 3 numbers onfrom 3 numbers on, between 3n−63n - 6 and 2⌊log⁡2 n⌋(⌊n/2⌋+n−2)2 \lfloor \log_2\, n \rfloor (\lfloor n / 2 \rfloor + n - 2); at 7, between 15 and 32
how the comparisons grow in each case
tight, Θ\ThetaΘ(n)\Theta(n)Θ(n log⁡2 n)\Theta(n \,\log_2\, n)
ceiling, OOO(n)O(n)O(n log⁡2 n)O(n \,\log_2\, n)
floor, Ω\OmegaΩ(n)\Omega(n)Ω(n log⁡2 n)\Omega(n \,\log_2\, n)

extra memory: a few places, however long the row

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

numbersorders triedcheapest orderdearest orderaverage orderall equal
512091210.959
6720121715.1312
75,040162219.7915
840,320212925.8118
Every order of 1 to n tried, in comparisons, beside n equal numbers. Equal numbers always cost the least. Up to 6, some order of different numbers costs as little; at 7 and 8, none does.

where the formula comes from

Each count above, worked out in small steps. Every step names the line it uses, and each 'where does this come from?' box opens a fact from another page.

Why do nn equal numbers cost exactly 3n−63n - 6 comparisons, the fewest any row can?
  1. the move: one round each

    the line:
    a sift compares the childrenof its place, then stops\begin{gathered} \text{a sift compares the children} \\ \text{of its place, then stops} \end{gathered}
    siftplaceits childrencomparisons
    building24 and 52
    building12 and 32
    heap of 412 and 32
    heap of 312 and 32
    heap of 2121
    in all9
    Heap sort on 8, 8, 8, 8, 8, sift by sift. 4 comparisons build the heap, and 5 sort it.

    why it is allowed: With equal numbers no child is bigger, so every sift stops after its first round. The picture counts 8, 8, 8, 8, 8.

  2. the move: count the building

    the line:
    building compareseach child once\begin{gathered} \text{building compares} \\ \text{each child once} \end{gathered}

    why it is allowed: Each place with a child is sifted once, and every place but place 1 is the child of one place. So n−1n - 1 comparisons; 4 for 5 numbers.

  3. the move: count the sorting

    the line:
    sorting compares2(n−3)+1\begin{gathered} \text{sorting compares} \\ 2(n - 3) + 1 \end{gathered}

    why it is allowed: The tops of heaps of n−1n - 1 numbers down to 2 are sifted. The n−3n - 3 heaps of 3 or more give their top 2 children, as the heaps of 4 and 3 in the picture. The heap of 2 gives 1.

  4. the move: add them

    the line:
    B=(n−1)+2(n−3)+1B = (n - 1) + 2(n - 3) + 1

    why it is allowed: BB is the comparisons on equal numbers, by lines 2 and 3.

  5. the move: multiply out

    the line:
    B=(n−1)+(2n−6)+1B = (n - 1) + (2n - 6) + 1

    why it is allowed: Twice n−3n - 3 is 2n−62n - 6.

  6. the move: gather

    the line:
    B=3n−6B = 3n - 6

    why it is allowed: The 1s cancel. For 5 numbers, 4 + 4 + 1 is 9, as in the picture.

  7. the move: no row costs fewer

    the line:
    every row comparesat least this\begin{gathered} \text{every row compares} \\ \text{at least this} \end{gathered}

    why it is allowed: On any row, every sift compares at least the children of its place. Lines 2 and 3 count only those.

  8. the move: a ceiling

    the line:
    B≤3nB \le 3n

    why it is allowed: By line 6, taking 6 away.

  9. the move: read it as a bound

    the line:
    B∈O(n)B \in O(n)

    why it is allowed: By line 8, BB stays under 3 times nn.

  10. the move: a floor

    the line:
    B≥n for n≥3B \ge n \text{ for } n \ge 3

    why it is allowed: 3n−63n - 6 is nn plus 2n−62n - 6, and 2n−62n - 6 is at least 0 from 3 on. At 5, 9 is 5 + 4.

  11. the move: read it as a bound

    the line:
    B∈Ω(n)B \in \Omega(n)

    why it is allowed: By line 10.

  12. the move: ceiling and floor together

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

    why it is allowed: Lines 9 and 11 bound BB by the same growth, nn.

try it with a small nn: at n=5n = 5, line 4 gives B=9B = 9, which you can work out by hand

What count of comparisons can no row of nn numbers go past?
  1. the move: price a round

    the line:
    a round compares at most2 children, then stopsor goes one level down\begin{gathered} \text{a round compares at most} \\ \text{2 children, then stops} \\ \text{or goes one level down} \end{gathered}
    roundcomparesthen
    142 with 12, 31 with 42swap 12 with 42
    218 with 12, 7 with 18swap 12 with 18
    Sifting 12 down a heap of 6, whose height is 2. Two rounds of 2 comparisons; then 12 has no child, and it stops.

    why it is allowed: The picture sifts 12 in the first six places of 12, 42, 31, 18, 7, 23, 56. That is the row just after the first top swap, before the sift mends it.

  2. the move: count the rounds

    the line:
    a sift makes at most hrounds\begin{gathered} \text{a sift makes at most } h \\ \text{rounds} \end{gathered}
    depth01212345671234567
    A heap of 7 has levels 0, 1 and 2, so height 2. Only the marked places, on levels 0 and 1, have children, so only they can hold a round.

    why it is allowed: A round needs a child below, and the deepest level has none. So only the hh levels above it can hold a round.

  3. the move: smaller heaps are no taller

    the line:
    the heaps of n−1 down to 2are no taller than h\begin{gathered} \text{the heaps of } n - 1 \text{ down to 2} \\ \text{are no taller than } h \end{gathered}

    why it is allowed: Taking the last place off never adds a level. The heap of 6 in line 1's picture has height 2, as 7 does.

  4. the move: count the sifts

    the line:
    building sifts each parent;sorting sifts n−2 tops\begin{gathered} \text{building sifts each parent;} \\ \text{sorting sifts } n - 2 \text{ tops} \end{gathered}
    partsiftsrounds each at mostcomparisons at most
    building3212
    sorting5220
    in all832
    For 7 numbers: 3 parents and 5 tops, each sift at most 2 rounds of 2 comparisons. That makes 32.

    why it is allowed: A parent is a place with a child. Sorting sifts the top after every swap but the last, which leaves one number. The picture counts them for 7.

  5. the move: multiply

    the line:
    U=2h(P+n−2)U = 2h(P + n - 2)

    why it is allowed: UU is a count no row goes past, by lines 1 to 4. hh is the height and PP the parents. For 7, hh is 2 and PP is 3.

  6. the move: name the height

    the line:
    U=2⌊log⁡2 n⌋(P+n−2)U = 2 \lfloor \log_2\, n \rfloor (P + n - 2)
    where does this come from?
    question 3 of the page trees and their wordsA tree of nn places kept in a row. What is its height?
    1. the move: the last place is the deepest

      the line:
      place n lies onthe last level\begin{gathered} \text{place } n \text{ lies on} \\ \text{the last level} \end{gathered}

      why it is allowed: The row fills the levels in order, so its last place, place nn, is on the last level. So the height is the depth of place nn.

    2. the move: each step up halves

      the line:
      a step up halves the place,rounding down\begin{gathered} \text{a step up halves the place,} \\ \text{rounding down} \end{gathered}
      13223451678910012345678910
      From place 10 up to the root, place 1, each step halving and rounding down, 10, 5, 2, 1, the steps counted beside them. Three steps, so place 10 has depth 3.

      why it is allowed: By question 2 of the page trees and their words, the parent of place ii is place ⌊i/2⌋\lfloor i / 2 \rfloor. From place 10 the steps up go 5, 2, 1.

    3. the move: count the steps

      the line:
      H=halvings, rounding down,that take n to 1\begin{gathered} H = \text{halvings, rounding down,} \\ \text{that take } n \text{ to 1} \end{gathered}

      why it is allowed: Let HH be the height. By lines 1 and 2 it is the steps from place nn up to place 1, each one halving, rounding down.

    4. the move: use halving and logarithms

      the line:
      H=⌊log⁡2 n⌋H = \lfloor \log_2\, n \rfloor
      where does this come from?
      question 2 of the page halving and logarithmsHalve nn, rounding down each time. How many halvings reach 1?
      1. the move: name the log rounded down

        the line:
        K=⌊log⁡2 n⌋K = \lfloor \log_2\, n \rfloor
        numberlog× 2+ 14283164113.46352.322211100
        Rounding down, 11 halves to 5, 2 and 1. In blue, each log rounded down: 3, 2, 1, 0, one less at each halving.

        why it is allowed: Here nn is the number halved, from 2 up; for 11, KK is 3.

      2. the move: rounding down never adds

        the line:
        ⌊log⁡2 n⌋≤log⁡2 n\lfloor \log_2\, n \rfloor \le \log_2\, n

        why it is allowed: For 11, 3 is at most 3.46.

      3. the move: rounding down takes off less than 1

        the line:
         log⁡2 n<⌊log⁡2 n⌋+1\begin{gathered} \,\log_2\, n \\ < \lfloor \log_2\, n \rfloor + 1 \end{gathered}

        why it is allowed: For 11, 4 is above 3.46.

      4. the move: raise 2 to each side of line 2

        the line:
        2⌊log⁡2 n⌋≤2log⁡2 n2^{\lfloor \log_2\, n \rfloor} \le 2^{\log_2\, n}

        why it is allowed: 2 raised to a bigger power gives a bigger number. For 11, 8 is at most about 11.

      5. the move: 2 to the log of n is n

        the line:
        2⌊log⁡2 n⌋≤n2^{\lfloor \log_2\, n \rfloor} \le n

        why it is allowed: By what a log is. For 11, 8 is at most 11.

      6. the move: raise 2 to each side of line 3

        the line:
        2log⁡2 n<2⌊log⁡2 n⌋+12^{\log_2\, n} < 2^{\lfloor \log_2\, n \rfloor + 1}

        why it is allowed: As in line 4. For 11, about 11 is below 16.

      7. the move: 2 to the log of n is n

        the line:
        n<2⌊log⁡2 n⌋+1n < 2^{\lfloor \log_2\, n \rfloor + 1}

        why it is allowed: As in line 5. For 11, 11 is below 16.

      8. the move: halve both sides of line 5

        the line:
        2⌊log⁡2 n⌋/2≤n/22^{\lfloor \log_2\, n \rfloor} / 2 \le n / 2

        why it is allowed: For 11, 4 is at most 5.5, which is not whole.

      9. the move: write the half as a power

        the line:
        2⌊log⁡2 n⌋−1≤n/22^{\lfloor \log_2\, n \rfloor - 1} \le n / 2

        why it is allowed: Half a power of 2 has one 2 fewer. Half of 8 is 4.

      10. the move: round the half down

        the line:
        2⌊log⁡2 n⌋−1≤⌊n/2⌋2^{\lfloor \log_2\, n \rfloor - 1} \le \lfloor n / 2 \rfloor

        why it is allowed: ⌊n/2⌋\lfloor n / 2 \rfloor is the half rounded down, 5 for 11. A whole number at most 5.5 is at most 5. The left side, 4 for 11, is whole, as KK is at least 1 for nn from 2 up.

      11. the move: halve both sides of line 7

        the line:
        n/2<2⌊log⁡2 n⌋+1/2n / 2 < 2^{\lfloor \log_2\, n \rfloor + 1} / 2

        why it is allowed: For 11, 5.5 is below 8.

      12. the move: write the half as a power

        the line:
        n/2<2⌊log⁡2 n⌋n / 2 < 2^{\lfloor \log_2\, n \rfloor}

        why it is allowed: As in line 9. Half of 16 is 8.

      13. the move: round the half down

        the line:
        ⌊n/2⌋<2⌊log⁡2 n⌋\lfloor n / 2 \rfloor < 2^{\lfloor \log_2\, n \rfloor}

        why it is allowed: Rounding down never adds. For 11, 5 is below 8.

      14. the move: take the log of line 10

        the line:
         log⁡2 2⌊log⁡2 n⌋−1≤log⁡2 ⌊n/2⌋\begin{gathered} \,\log_2\, 2^{\lfloor \log_2\, n \rfloor - 1} \\ \le \log_2\, \lfloor n / 2 \rfloor \end{gathered}

        why it is allowed: A bigger number has a bigger log. For 11, the log of 4 is at most the log of 5.

      15. the move: the log of a power of 2 is the power

        the line:
        ⌊log⁡2 n⌋−1≤log⁡2 ⌊n/2⌋\begin{gathered} \lfloor \log_2\, n \rfloor - 1 \\ \le \log_2\, \lfloor n / 2 \rfloor \end{gathered}

        why it is allowed: For 11, the log of 4 is 2, at most about 2.32.

      16. the move: take the log of line 13

        the line:
         log⁡2 ⌊n/2⌋<log⁡2 2⌊log⁡2 n⌋\begin{gathered} \,\log_2\, \lfloor n / 2 \rfloor \\ < \log_2\, 2^{\lfloor \log_2\, n \rfloor} \end{gathered}

        why it is allowed: As in line 14. For 11, the log of 5 is below the log of 8.

      17. the move: the log of a power of 2 is the power

        the line:
         log⁡2 ⌊n/2⌋<⌊log⁡2 n⌋\begin{gathered} \,\log_2\, \lfloor n / 2 \rfloor \\ < \lfloor \log_2\, n \rfloor \end{gathered}

        why it is allowed: For 11, about 2.32 is below 3.

      18. the move: round the log down

        the line:
        ⌊log⁡2 ⌊n/2⌋⌋=⌊log⁡2 n⌋−1\begin{gathered} \lfloor \log_2\, \lfloor n / 2 \rfloor \rfloor \\ = \lfloor \log_2\, n \rfloor - 1 \end{gathered}
        the numberat leastbelowits log rounded down
        118163
        5482
        2241
        1120
        Each halving takes 1 off the log rounded down.

        why it is allowed: By lines 15 and 17, the log of the half is at least one less than KK and below KK, so it rounds down to one less. For 11, about 2.32 rounds down to 2.

      19. the move: use line 18 again and again

        the line:
        after K halvings,rounding down,the log roundeddown is 0\begin{gathered} \text{after } K \text{ halvings,} \\ \text{rounding down,} \\ \text{the log rounded} \\ \text{down is 0} \end{gathered}

        why it is allowed: While the log rounded down is 1 or more, the number is at least 2 to the power 1, which is 2. So line 18 takes 1 off each halving, down to 0 after KK. For 11, 3, 2, 1, 0.

      20. the move: a log rounded down to 0 belongs to 1

        the line:
        K halvings,rounding down,bring n to 1\begin{gathered} K \text{ halvings,} \\ \text{rounding down,} \\ \text{bring } n \text{ to 1} \end{gathered}

        why it is allowed: Such a log is at least 0 and below 1, so its number is at least 1 and below 2. It is 1.

      the whole page: halving and logarithms

      why it is allowed: The page on halving shows that halving nn, rounding down, reaches 1 after ⌊log⁡2 n⌋\lfloor \log_2\, n \rfloor halvings. For 10, the biggest power of 2 not past it is 8, three 2s multiplied, so 3 halvings, as in the picture. A tree of 1 place needs none, and the log of 1 is 0.

    5. the move: read it

      the line:
      10 places: height 31,000 places: height 9\begin{gathered} 10 \text{ places: height 3} \\ 1{,}000 \text{ places: height 9} \end{gathered}

      why it is allowed: 10 lies between 8 and 16, so its log rounded down is 3. 1,000 lies between 512 and 1,024, so 9. Doubling the places adds 1 to the height. 20 places end at place 20, the first child of place 10 by question 2 of the page trees and their words, one level below where 10 places end.

    the whole page: trees and their words

    why it is allowed: The box 'where does this come from?' under this line shows a tree of nn places kept in a row has height ⌊log⁡2 n⌋\lfloor \log_2\, n \rfloor.

  7. the move: count the parents

    the line:
    children at 2p and 2p+1, soU=2⌊log⁡2 n⌋(⌊n/2⌋+n−2)\begin{gathered} \text{children at } 2p \text{ and } 2p + 1 \text{, so} \\ U = 2 \lfloor \log_2\, n \rfloor (\lfloor n / 2 \rfloor + n - 2) \end{gathered}
    where does this come from?
    question 2 of the page trees and their wordsFrom place ii of a tree kept in a row, which places lie one step down, and which one step up?
    1. the move: find where a level starts

      the line:
      level d startsat place 2d\begin{gathered} \text{level } d \text{ starts} \\ \text{at place } 2^d \end{gathered}
      depth012312345678910123456789100123
      The tree of 10 places. Its levels start at places 1, 2, 4 and 8, each block in the row starting where the one before ends.

      why it is allowed: Say place ii is on level dd. No level starts until the one above it is used up, so the levels above level dd are full. For level 3, levels 0 to 2 hold 1, 2 and 4, which is 7 places, so level 3 starts at place 8. In general the levels above form a full tree whose height is one less than dd. By question 1 of the page trees and their words it holds one place fewer than 2d2^d, so level dd starts at place 2d2^d. Level 0 is the root alone, at place 1, and 2 to the power 0 is 1.

    2. the move: count what comes before the first child

      the line:
      C=2d+1+2(i−2d)C = 2^{d + 1} + 2(i - 2^d)
      1234567891012345678910
      Places 2 and 3 take their children in turn, 4 and 5, then 6 and 7. So the first child of place 3 comes after the two of place 2.

      why it is allowed: Let CC be the place of the first child of ii. On level dd, i−2di - 2^d places come before ii. The row fills level d+1d + 1 from its left end, each place's children in turn, so each place before ii has its two children there before ii's first. That level starts at place 2d+12^{d + 1}. For place 3, one place comes before it on level 1, so its first child is 4 + 2, place 6.

    3. the move: multiply out

      the line:
      C=2d+1+2i−2⋅2dC = 2^{d + 1} + 2i - 2 \cdot 2^d

      why it is allowed: Twice i−2di - 2^d is twice ii less twice 2d2^d.

    4. the move: tidy the power

      the line:
      C=2d+1+2i−2d+1C = 2^{d + 1} + 2i - 2^{d + 1}

      why it is allowed: Twice 2d2^d is 2d+12^{d + 1}.

    5. the move: cancel

      the line:
      C=2iC = 2i

      why it is allowed: The first and last terms cancel. For place 3, twice 3 is 6, as line 2 found.

    6. the move: the second child is next

      the line:
      its second childis place 2i+1\begin{gathered} \text{its second child} \\ \text{is place } 2i + 1 \end{gathered}

      why it is allowed: The two children stand side by side. For place 3, places 6 and 7. A place whose first child would fall past the end of the row is a leaf.

    7. the move: halve a first child

      the line:
      ⌊2i/2⌋=i\lfloor 2i / 2 \rfloor = i

      why it is allowed: The floor brackets round down, as on the page on halving. Half of 2i2i is ii exactly, so rounding changes nothing.

    8. the move: halve a second child

      the line:
      ⌊(2i+1)/2⌋=i\lfloor (2i + 1) / 2 \rfloor = i

      why it is allowed: Half of 2i+12i + 1 is ii and a half, which rounds down to ii.

    9. the move: read it

      the line:
      past the root, the parentof place i is place ⌊i/2⌋\begin{gathered} \text{past the root, the parent} \\ \text{of place } i \text{ is place } \lfloor i / 2 \rfloor \end{gathered}

      why it is allowed: Every place but the root is the first or the second child of some place, twice it or one more, by lines 5 and 6. Halving it and rounding down gives that place back, by lines 7 and 8. For places 6 and 7, place 3.

    the whole page: trees and their words

    why it is allowed: That box finds each place's children. Place pp is a parent when twice pp is at most nn, so places 1 to ⌊n/2⌋\lfloor n / 2 \rfloor. For 7, UU is 2 × 2 × (3 + 5), which is 32.

  8. the move: a simpler bracket

    the line:
    U≤2⌊log⁡2 n⌋(n2+n)U \le 2 \lfloor \log_2\, n \rfloor \Bigl(\frac{n}{2} + n\Bigr)

    why it is allowed: Rounding down makes no bigger, and taking 2 away makes less. At 7, 3 + 5 is 8, at most 3.5 + 7, which is 10.5.

  9. the move: add the halves

    the line:
    U≤2⌊log⁡2 n⌋×3n2U \le 2 \lfloor \log_2\, n \rfloor \times \frac{3n}{2}

    why it is allowed: Half of nn and nn make 3 halves of nn.

  10. the move: multiply

    the line:
    U≤3n⌊log⁡2 n⌋U \le 3n \lfloor \log_2\, n \rfloor

    why it is allowed: Twice 3 halves is 3.

  11. the move: drop the rounding

    the line:
    U≤3n log⁡2 nU \le 3n \,\log_2\, n

    why it is allowed: Rounding down makes no bigger.

  12. the move: read it as a bound

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

    why it is allowed: By line 11, UU stays under 3 times n log⁡2 nn \,\log_2\, n.

  13. the move: read it

    the line:
    no row goes past U\begin{gathered} \text{no row goes past } U \end{gathered}

    why it is allowed: Lines 1 to 4 hold on every row. Of the 5,040 orders of 7 numbers, the dearest costs 22, under 32.

try it with a small nn: at n=7n = 7, line 5 gives U=32U = 32, which you can work out by hand

How does the dearest row's cost WW grow?
  1. the move: name it

    the line:
    W: the most any orderof n numbers costs\begin{gathered} W \text{: the most any order} \\ \text{of } n \text{ numbers costs} \end{gathered}

    why it is allowed: This page finds WW by trying every order, for short rows. By the question on the ceiling, WW is at most UU.

  2. the move: the fewest doublings

    the line:
    F=doublings of 1 that reach1×2×⋯×n\begin{gathered} F = \text{doublings of 1 that reach} \\ 1 \times 2 \times \dots \times n \end{gathered}

    why it is allowed: FF counts the doublings 1, 2, 4 and on until they reach the product. At 7 the product is 5,040; 4,096 falls short, 8,192 reaches it, so 13. FF is a floor under WW, which is 22 at 7.

  3. the move: count the orders

    the line:
    F=doublings of 1 that reach n!\begin{gathered} F = \text{doublings of 1 that reach } n! \end{gathered}
    where does this come from?
    question 1 of the page the sorting floorIn how many orders can nn different numbers stand?
    1. the move: the first place

      the line:
      the first place takesany of the n numbers\begin{gathered} \text{the first place takes} \\ \text{any of the } n \text{ numbers} \end{gathered}

      why it is allowed: Any of the nn numbers can stand first, so any of 3 for 1, 2 and 3.

    2. the move: the second place

      the line:
      each first choice goes onin n−1 ways\begin{gathered} \text{each first choice goes on} \\ \text{in } n - 1 \text{ ways} \end{gathered}
      firstsecondthird
      123
      132
      213
      231
      312
      321
      The 6 orders of 1, 2 and 3, place by place.

      why it is allowed: From 2 numbers on, each first choice leaves n−1n - 1 for the second place. For 1, 2 and 3, 3 times 2 is 6, and the number left fills the third.

    3. the move: on to the last

      the line:
      R=n×(n−1)×⋯×1R = n \times (n - 1) \times \dots \times 1

      why it is allowed: Let RR be the number of orders. As in line 2, each place has one choice fewer, down to 1, and the choices multiply. For 3, 3 × 2 × 1 is 6.

    4. the move: n factorial

      the line:
      R=n!R = n!

      why it is allowed: nn down to 1, multiplied, is written n!n!, read nn factorial.

    5. the move: read it

      the line:
      each number more multipliesthe orders\begin{gathered} \text{each number more multiplies} \\ \text{the orders} \end{gathered}

      why it is allowed: By line 3, one number more adds a factor. 3 numbers stand in 6 orders, 4 in 24 and 5 in 120.

    the whole page: the sorting floor

    why it is allowed: The box under this line shows that nn different numbers stand in 1×2×⋯×n1 \times 2 \times \dots \times n orders, written n!n!.

  4. the move: name the sorting floor

    the line:
    F=⌈log⁡2 n!⌉F = \lceil \log_2\, n! \rceil
    where does this come from?
    question 3 of the page the sorting floorAt least how many comparisons does a comparing sort's worst row of nn different numbers take?
    1. the move: answers decide

      the line:
      two rows that givethe same answersare treated the same\begin{gathered} \text{two rows that give} \\ \text{the same answers} \\ \text{are treated the same} \end{gathered}
      the rowanswersmovesit ends as
      1, 3, 2no yes noswap the last two1, 2, 3
      10, 30, 20no yes noswap the last two10, 20, 30
      Bubble sort walks left to right, asking each pair of neighbours 'is the left bigger?' and swapping on a yes. Each walk is one pair shorter, until one swaps nothing or no pair is left.

      why it is allowed: A comparing sort with no random choices learns only from its answers, so its next comparison and move hang only on its answers so far. So rows giving the same answers get the same comparisons and moves, and stop together.

    2. the move: one list per order

      the line:
      two orders of the same numbersget different answer lists\begin{gathered} \text{two orders of the same numbers} \\ \text{get different answer lists} \end{gathered}

      why it is allowed: Pretend two different orders of the same numbers gave the same answers. By line 1 they get the same moves, carrying what stands at each place to the same place on both. So they end different, at most one in order: a swap puts 2, 1 in order but not 1, 2. Yet the sort puts every row in order, so each order gets its own list.

    3. the move: fill out short lists

      the line:
      with W the most comparisonson any order, every order getsa list of exactly W answers\begin{gathered} \text{with } W \text{ the most comparisons} \\ \text{on any order, every order gets} \\ \text{a list of exactly } W \text{ answers} \end{gathered}
      3 2 13 1 22 1 32 3 11 3 21 2 3yesnoa yes added
      Short lists carried down to 3 answers by dotted yeses. No no, for 1, 2, 3, begins no other list, so no no yes is new.

      why it is allowed: Let WW be the most comparisons on any order. Fill each shorter list out to WW answers with pretend yeses, so all have the one length line 4 counts. Filling adds only at the end. And no list begins another: if one did, by line 1 its row and the longer one's would stop together, so the longer would not go on. So the filled lists stay different.

    4. the move: count both

      the line:
      2W is at least n!\begin{gathered} 2^W \text{ is at least } n! \end{gathered}
      nnordersthe floorits lists
      3638
      424532
      51207128
      840,3201665,536
      12479,001,60029536,870,912
      One answer fewer gives half the lists, too few.

      why it is allowed: Each answer doubles the lists, so WW answers make 2W2^W, against n!n! orders. By lines 2 and 3, lists are at least as many as orders. For 4, the 16 lists of 4 answers are too few for 24.

    5. the move: name the floor

      the line:
      F=the fewest doublingsof 1 that reach n!\begin{gathered} F = \text{the fewest doublings} \\ \text{of 1 that reach } n! \end{gathered}

      why it is allowed: Let FF be the fewest doublings of 1 that reach n!n! or pass it. For 4, four doublings reach only 16, short of 24, and the fifth, 32, passes it.

    6. the move: at least FF

      the line:
      W is at least F\begin{gathered} W \text{ is at least } F \end{gathered}

      why it is allowed: By line 4, WW doublings of 1 reach n!n!, and by line 5 no fewer than FF do. So WW is at least FF.

    7. the move: halving and logarithms

      the line:
      F=⌈log⁡2 n!⌉F = \lceil \log_2\, n! \rceil
      where does this come from?
      question 4 of the page halving and logarithmsHalve nn, rounding up each time. How many halvings reach 1?
      1. the move: name the log rounded up

        the line:
        C=⌈log⁡2 n⌉C = \lceil \log_2\, n \rceil

        why it is allowed: Here nn is the number halved, from 2 up. For 11, CC is 4.

      2. the move: rounding up never takes off

        the line:
        log⁡2 n≤⌈log⁡2 n⌉\log_2\, n \le \lceil \log_2\, n \rceil

        why it is allowed: The bracket is CC. For 11, 3.46 is at most 4.

      3. the move: rounding up adds less than 1

        the line:
        ⌈log⁡2 n⌉−1<log⁡2 n\lceil \log_2\, n \rceil - 1 < \log_2\, n

        why it is allowed: For 11, 3 is below 3.46.

      4. the move: raise 2 to each side of line 2

        the line:
        2log⁡2 n≤2⌈log⁡2 n⌉2^{\log_2\, n} \le 2^{\lceil \log_2\, n \rceil}

        why it is allowed: As in line 4 of question 2 of the page halving and logarithms.

      5. the move: 2 to the log of n is n

        the line:
        n≤2⌈log⁡2 n⌉n \le 2^{\lceil \log_2\, n \rceil}

        why it is allowed: As in line 5 of question 2 of the page halving and logarithms. For 11, 11 is at most 16.

      6. the move: raise 2 to each side of line 3

        the line:
        2⌈log⁡2 n⌉−1<2log⁡2 n2^{\lceil \log_2\, n \rceil - 1} < 2^{\log_2\, n}

        why it is allowed: As in line 4.

      7. the move: 2 to the log of n is n

        the line:
        2⌈log⁡2 n⌉−1<n2^{\lceil \log_2\, n \rceil - 1} < n

        why it is allowed: As in line 5. For 11, 8 is below 11.

      8. the move: halve both sides of line 5

        the line:
        n/2≤2⌈log⁡2 n⌉/2n / 2 \le 2^{\lceil \log_2\, n \rceil} / 2

        why it is allowed: Halving both sides keeps it true.

      9. the move: write the half as a power

        the line:
        n/2≤2⌈log⁡2 n⌉−1n / 2 \le 2^{\lceil \log_2\, n \rceil - 1}

        why it is allowed: As in line 9 of question 2 of the page halving and logarithms. For 11, 5.5 is at most 8.

      10. the move: round the half up

        the line:
        ⌈n/2⌉≤2⌈log⁡2 n⌉−1\lceil n / 2 \rceil \le 2^{\lceil \log_2\, n \rceil - 1}

        why it is allowed: ⌈n/2⌉\lceil n / 2 \rceil is the half rounded up: the smallest whole number at or above it, 6 for 11. The right side, 8 for 11, is whole, as CC is at least 1. By line 9 it is at or above the half, so no smaller than the half rounded up.

      11. the move: halve both sides of line 7

        the line:
        2⌈log⁡2 n⌉−1/2<n/22^{\lceil \log_2\, n \rceil - 1} / 2 < n / 2

        why it is allowed: Halving both sides keeps it true.

      12. the move: write the half as a power

        the line:
        2⌈log⁡2 n⌉−2<n/22^{\lceil \log_2\, n \rceil - 2} < n / 2
        numberlog× 2+ 11/2−1102142
        One half, a step left of 1, is 2 to the power minus 1.

        why it is allowed: As in line 9 of question 2 of the page halving and logarithms. For 11, 4 is below 5.5. For 2, CC is 1, so this is 2 to the power minus 1, one half, as drawn.

      13. the move: round the half up

        the line:
        2⌈log⁡2 n⌉−2<⌈n/2⌉2^{\lceil \log_2\, n \rceil - 2} < \lceil n / 2 \rceil

        why it is allowed: Rounding up never takes off. For 11, 4 is below 6.

      14. the move: take the log of line 10

        the line:
        log⁡2 ⌈n/2⌉≤log⁡2 2⌈log⁡2 n⌉−1\log_2\, \lceil n / 2 \rceil \le \log_2\, 2^{\lceil \log_2\, n \rceil - 1}

        why it is allowed: As in line 14 of question 2 of the page halving and logarithms.

      15. the move: the log of a power of 2 is the power

        the line:
        log⁡2 ⌈n/2⌉≤⌈log⁡2 n⌉−1\log_2\, \lceil n / 2 \rceil \le \lceil \log_2\, n \rceil - 1

        why it is allowed: For 11, the log of 6, about 2.58, is at most 3.

      16. the move: take the log of line 13

        the line:
        log⁡2 2⌈log⁡2 n⌉−2<log⁡2 ⌈n/2⌉\log_2\, 2^{\lceil \log_2\, n \rceil - 2} < \log_2\, \lceil n / 2 \rceil

        why it is allowed: As in line 14. For 2, the log of one half is minus 1, below the log of 1, which is 0.

      17. the move: the log of a power of 2 is the power

        the line:
        ⌈log⁡2 n⌉−2<log⁡2 ⌈n/2⌉\lceil \log_2\, n \rceil - 2 < \log_2\, \lceil n / 2 \rceil

        why it is allowed: For 11, 2 is below about 2.58.

      18. the move: round the log up

        the line:
        ⌈log⁡2 ⌈n/2⌉⌉=⌈log⁡2 n⌉−1\lceil \log_2\, \lceil n / 2 \rceil \rceil = \lceil \log_2\, n \rceil - 1
        the numberaboveat mostits log rounded up
        118164
        6483
        3242
        2121
        11/210
        Each halving takes 1 off the log rounded up.

        why it is allowed: By lines 15 and 17, the log of the half is above two less than CC and at most one less, so it rounds up to one less. For 11, about 2.58 rounds up to 3.

      19. the move: use line 18 again and again

        the line:
        after C halvings,rounding up, the logrounded up is 0\begin{gathered} \text{after } C \text{ halvings,} \\ \text{rounding up, the log} \\ \text{rounded up is 0} \end{gathered}

        why it is allowed: While the log rounded up is 1 or more, the log is above 0, so the number is above 1: at least 2. So line 18 takes 1 off each halving, and the number stays 2 or more until exactly CC halvings. For 11, 4, 3, 2, 1, 0.

      20. the move: a log rounded up to 0 belongs to 1

        the line:
        C halvings, rounding up,bring n to 1\begin{gathered} C \text{ halvings, rounding up,} \\ \text{bring } n \text{ to 1} \end{gathered}

        why it is allowed: Such a log is at most 0, so its number is at most 1, and so is 1.

      21. the move: read lines 5 and 7 as doublings

        the line:
        C doublings of 1 reach n,one fewer do not\begin{gathered} C \text{ doublings of 1 reach } n, \\ \text{one fewer do not} \end{gathered}

        why it is allowed: Doubling 1 gives the powers of 2. By line 5, CC doublings get to or past nn; by line 7, one fewer stay below. For 11, 8 stays below and 16 gets past.

      22. the move: count merge sort's rounds

        the line:
        merge sort on this sitemakes C rounds\begin{gathered} \text{merge sort on this site} \\ \text{makes } C \text{ rounds} \end{gathered}
        the row: 5, 9, 2, 7, 11, 1, 8, 3, 10, 6, 411111111111start222221round 1443round 283round 311round 42a run, its length insideno partner, carried downthe first runall in one runa merge in round 2, its numbers59272579goes straight in, the other run used up
        Round 2 merges 5, 9 and 2, 7 into 2, 5, 7, 9.
        after roundruns
        start11
        16
        23
        32
        41
        The first run holds 1, 2, 4, 8, then all 11: four rounds. The count of runs is 11 halved, rounding up.

        why it is allowed: Merge sort starts from runs of 1, whatever the row. Each round merges neighbouring runs in pairs, so the first run doubles, the last round taking only what is left. By line 21 it holds all nn after CC rounds, not fewer.

      23. the move: read it

        the line:
        C halvings,rounding up, andC rounds of merge sort\begin{gathered} C \text{ halvings,} \\ \text{rounding up, and} \\ C \text{ rounds of merge sort} \end{gathered}

        why it is allowed: By lines 20 and 22, one count gives both the halvings and merge sort's rounds. For 11, four of each.

      the whole page: halving and logarithms

      why it is allowed: The fewest doublings of 1 reaching a number from 2 up are its log to base 2 rounded up: 5 for 24. The box under this line, from the page halving and logarithms, shows it at its lines 5 and 7.

    8. the move: read it

      the line:
      no comparing sort makes feweron its worst row\begin{gathered} \text{no comparing sort makes fewer} \\ \text{on its worst row} \end{gathered}

      why it is allowed: By lines 6 and 7, every comparing sort that makes no random choices makes at least ⌈log⁡2 n!⌉\lceil \log_2\, n! \rceil comparisons on its worst row of nn. It is only a floor: for 12 numbers it is 29, yet the best sort for 12 needs 30 on its worst row. An outside result, and no line here rests on it (Mark Wells, 1965; Knuth, The Art of Computer Programming, volume 3, section 5.3.1).

    the whole page: the sorting floor

    why it is allowed: The box under this line counts those doublings as the log of n!n! rounded up, the sorting floor.

  5. the move: the dearest needs FF

    the line:
    W is at least F\begin{gathered} W \text{ is at least } F \end{gathered}
    numbersfloor FFdearest WWceiling UU
    571220
    6101728
    7132232
    8162960
    Every order of 1 to n tried. The dearest always lies between the floor and the ceiling.

    why it is allowed: The box at line 4 shows it, at its line 6. No comparing sort's dearest row costs fewer. The picture tries it.

  6. the move: write the log as a sum

    the line:
    F=⌈log⁡2 1+log⁡2 2+⋯+log⁡2 n⌉F = \lceil \log_2\, 1 + \log_2\, 2 + \dots + \log_2\, n \rceil
    where does this come from?
    question 4 of the page the sorting floorHow does log⁡2 n!\log_2\, n! grow?
    1. the move: name the log

      the line:
      G=log⁡2 n!G = \log_2\, n!

      why it is allowed: Let GG be the log to base 2 of n!n!, for nn from 4 as lines 12 and 15 need. For 8, about 15.30.

    2. the move: factors at most n

      the line:
      n!≤nnn! \le n^n

      why it is allowed: n!n! multiplies nn whole numbers, each at most nn. Putting nn for each gives nnn^n, read nn to the power nn, no smaller. For 8, 40,320 against 16,777,216.

    3. the move: bigger number, bigger log

      the line:
      log⁡2 n!≤log⁡2 nn\log_2\, n! \le \log_2\, n^n

      why it is allowed: On a number line of powers of 2, 16 stands right of 8, and its log, 4, right of 8's log, 3. Any two numbers go the same way, as the page halving and logarithms shows, so line 2 holds for the logs.

    4. the move: into line 1

      the line:
      G≤log⁡2 nnG \le \log_2\, n^n

      why it is allowed: By line 3, as GG is the log of n!n!.

    5. the move: log of a power

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

      why it is allowed: For 8: 8 is three 2s, so 8 to the power 8 is 24 2s, since multiplying powers of 2 adds the powers. Each number is 2 raised to its log, so the log of a product adds the logs. nnn^n is a product of nn factors, each nn, so its log is nn times log⁡2 n\log_2\, n.

    6. the move: keep the top half

      the line:
      n!≥the product ofits ⌈n/2⌉ factorsabove half of n\begin{gathered} n! \ge \text{the product of} \\ \text{its } \lceil n/2 \rceil \text{ factors} \\ \text{above half of } n \end{gathered}

      why it is allowed: Drop the factors 1 to half of nn rounded down; each is at least 1, so the product gets no bigger. Half of nn rounded down and rounded up add up to nn, as 3 and 4 for 7. So ⌈n/2⌉\lceil n/2 \rceil are kept, read half of nn rounded up.

    7. the move: half of n for each

      the line:
      n!≥(n2)⌈n/2⌉n! \ge \left(\frac{n}{2}\right)^{\lceil n/2 \rceil}
      for 8multiplied
      8 down to 140,320
      8 × 7 × 6 × 51,680
      4 × 4 × 4 × 4256
      Drop 4 down to 1, then put 4, half of 8, for each factor kept.

      why it is allowed: Each kept factor is above half of nn, so putting half of nn for each gives no bigger product.

    8. the move: bigger number, bigger log

      the line:
      log⁡2 n!≥log⁡2(n2)⌈n/2⌉\log_2\, n! \ge \log_2 \left(\frac{n}{2}\right)^{\lceil n/2 \rceil}

      why it is allowed: As in line 3.

    9. the move: into line 1

      the line:
      G≥log⁡2(n2)⌈n/2⌉G \ge \log_2 \left(\frac{n}{2}\right)^{\lceil n/2 \rceil}

      why it is allowed: By line 8, as GG is the log of n!n!.

    10. the move: log of a power

      the line:
      G≥⌈n2⌉log⁡2 n2G \ge \left\lceil \frac{n}{2} \right\rceil \log_2\, \frac{n}{2}

      why it is allowed: As in line 5. For 8, 4 times 2.

    11. the move: rounding up

      the line:
      ⌈n2⌉≥n2\left\lceil \frac{n}{2} \right\rceil \ge \frac{n}{2}

      why it is allowed: Rounding up makes no smaller, as 3.5 goes up to 4.

    12. the move: log of half of n

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

      why it is allowed: From 4 on, half of nn is at least 2, whose log is 1; by line 3, bigger numbers have bigger logs.

    13. the move: drop the rounding

      the line:
      G≥n2 log⁡2 n2G \ge \frac{n}{2} \,\log_2\, \frac{n}{2}

      why it is allowed: By line 11, half of nn is at most ⌈n/2⌉\lceil n/2 \rceil, as 3.5 against 4 for 7. Each multiplies the log of half of nn, above zero by line 12, so putting half of nn in line 10 makes it no bigger.

    14. the move: halving takes 1 off

      the line:
      G≥n2(log⁡2 n−1)G \ge \frac{n}{2} \left(\log_2\, n - 1\right)

      why it is allowed: nn is 2 times half of nn, and the log of 2 is 1. So by line 5 the log of half of nn is log⁡2 n−1\log_2\, n - 1. For 8, the log of 4 is 3 less 1.

    15. the move: a fact about n

      the line:
      log⁡2 n2≤log⁡2 n−1\frac{\log_2\, n}{2} \le \log_2\, n - 1

      why it is allowed: From 4 on, log⁡2 n\log_2\, n is at least 2, so half of it is at least 1, and taking 1 away leaves at least half. For 8, 1.5 against 2.

    16. the move: the smaller part

      the line:
      G≥n2×log⁡2 n2G \ge \frac{n}{2} \times \frac{\log_2\, n}{2}

      why it is allowed: By line 15, putting half of log⁡2 n\log_2\, n for log⁡2 n−1\log_2\, n - 1 in line 14 makes it no bigger, as in line 13. For 8, 4 times 1.5, 6.

    17. the move: multiply out

      the line:
      G≥n log⁡2 n4G \ge \frac{n \,\log_2\, n}{4}
      the lognumbers0102030400246810the lognumbers0102030400246810
      • n log⁡2 nn \,\log_2\, n
      • the log of n!n!
      • a quarter of n log⁡2 nn \,\log_2\, n
      The log of n!n! between the other two, from 1 to 10 numbers. At 8: 24, about 15.30, and 6.

      why it is allowed: Half of nn times half of log⁡2 n\log_2\, n.

    18. the move: a ceiling

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

      why it is allowed: G∈O(n log⁡2 n)G \in O(n \,\log_2\, n), read GG is in big O of n log⁡2 nn \,\log_2\, n, says a fixed multiple of it is a ceiling of GG. By line 5, 1 times it, from 4 on.

    19. the move: a floor

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

      why it is allowed: G∈Ω(n log⁡2 n)G \in \Omega(n \,\log_2\, n), read big omega, says a fixed multiple, above zero, is a floor of GG, a floor on growth, not the sorting floor. By line 17, a quarter, from 4 on.

    20. the move: both

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

      why it is allowed: G∈Θ(n log⁡2 n)G \in \Theta(n \,\log_2\, n), read big theta, says both, by lines 18 and 19. GG grows like n log⁡2 nn \,\log_2\, n.

    the whole page: the sorting floor

    why it is allowed: The log of a product adds the logs, as the box under this line uses. The log of 4 × 8 = 32 is 5, which is 2 + 3, the logs of 4 and 8.

  7. the move: rounding up makes no smaller

    the line:
    F≥log⁡2 1+log⁡2 2+⋯+log⁡2 nF \ge \log_2\, 1 + \log_2\, 2 + \dots + \log_2\, n

    why it is allowed: By line 6.

  8. the move: a floor

    the line:
    F≥n log⁡2 n4 for n≥4F \ge \frac{n \,\log_2\, n}{4} \text{ for } n \ge 4
    numberslog⁡2 n\log_2\, nn log⁡2 nn \,\log_2\, na quarter of itFF
    42825
    8324616
    164641645
    F against a quarter of n log2 n, at 4, 8 and 16 numbers. F is always the bigger.

    why it is allowed: The box at line 6 shows the sum is at least this from 4 on, at its line 17. The picture tries it.

  9. the move: read it as a bound

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

    why it is allowed: By line 8, the fixed multiple a quarter, from 4 on.

  10. the move: a floor for WW

    the line:
    W grows at leastas fast as n log⁡2 n\begin{gathered} W \text{ grows at least} \\ \text{as fast as } n \,\log_2\, n \end{gathered}

    why it is allowed: By lines 5 and 9.

  11. the move: a ceiling for WW

    the line:
    W grows no fasterthan n log⁡2 n\begin{gathered} W \text{ grows no faster} \\ \text{than } n \,\log_2\, n \end{gathered}

    why it is allowed: By line 1, WW is at most UU, which the question on the ceiling finds is in O(n log⁡2 n)O(n \,\log_2\, n).

  12. the move: ceiling and floor together

    the line:
    W grows like n log⁡2 n:Θ(n log⁡2 n)\begin{gathered} W \text{ grows like } n \,\log_2\, n \text{:} \\ \Theta(n \,\log_2\, n) \end{gathered}

    why it is allowed: Lines 10 and 11 bound WW by the same growth.

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

How many orders can finish in fewer than kk comparisons?
  1. the move: few short lists

    the line:
    4 numbers: 24 orders,7 lists shorter than 3\begin{gathered} \text{4 numbers: 24 orders,} \\ \text{7 lists shorter than 3} \end{gathered}
    answerslists
    01
    12
    24
    fewer than 37
    Lists of 0, 1 and 2 answers, 7 in all. So at most 7 of the 24 orders of 4 numbers finish in fewer than 3 comparisons. Heap sort takes 6 or 7 on each.

    why it is allowed: This question sets up the average. For 4 numbers, take kk as 3. Only 7 lists have fewer than 3 answers, under half of 24.

  2. the move: one list each

    the line:
    each order needsits own list of answers\begin{gathered} \text{each order needs} \\ \text{its own list of answers} \end{gathered}
    comparisonslistsenough for 24 orders?
    12no
    24no
    38no
    416no
    532yes
    Each comparison doubles the lists. 4 numbers stand in 24 orders, each needing its own list, so some order takes at least 5 comparisons.

    why it is allowed: Two orders given the same list of answers are moved the same way, so one would end out of order. The box at line 4 of the question on the dearest row shows it, at its line 2.

  3. the move: choose k

    the line:
    k is ⌊log⁡2 n!⌋−1\begin{gathered} k \text{ is } \lfloor \log_2\, n! \rfloor - 1 \end{gathered}

    why it is allowed: For 4 numbers, the log of 24 is about 4.58, so kk is 3.

  4. the move: count the short lists

    the line:
    S=lists of 0,1,…,k−1 answersS = \text{lists of } 0, 1, \dots, k - 1 \text{ answers}

    why it is allowed: SS is the lists of fewer than kk answers.

  5. the move: lists of each length

    the line:
    S=1+2+4+⋯+2k−1S = 1 + 2 + 4 + \dots + 2^{k - 1}
    where does this come from?
    question 2 of the page the sorting floorHow many different lists of nn yes-or-no answers are there?
    1. the move: two answers

      the line:
      each answer isyes or no\begin{gathered} \text{each answer is} \\ \text{yes or no} \end{gathered}

      why it is allowed: Here nn counts answers, not numbers. Each comparison answers yes or no.

    2. the move: each answer doubles

      the line:
      each list goes onas a yes or as a no\begin{gathered} \text{each list goes on} \\ \text{as a yes or as a no} \end{gathered}
      answersthe listshow many
      0the empty list1
      1yes; no2
      2yes yes; yes no; no yes; no no4
      Each answer more doubles the lists, 1, 2, 4.

      why it is allowed: Each list goes on with a yes or a no, so each answer doubles the lists. No answers make one list, the empty one.

    3. the move: double n times

      the line:
      A=2×2×⋯×2A = 2 \times 2 \times \dots \times 2

      why it is allowed: Let AA be the number of lists of nn answers. By line 2, 1 doubled nn times. For 3, 2 × 2 × 2 is 8.

    4. the move: a power

      the line:
      A=2nA = 2^n

      why it is allowed: nn 2s multiplied are written 2n2^n, read 2 to the power nn. 2 to the power 0 is 1.

    5. the move: read it

      the line:
      each question more doublesthe lists\begin{gathered} \text{each question more doubles} \\ \text{the lists} \end{gathered}

      why it is allowed: By line 4, one answer more is one 2 more: 4 answers make 16 lists and 5 make 32.

    the whole page: the sorting floor

    why it is allowed: The box under this line shows each answer doubles the lists. There is 1 list of no answers, 2 of one, 4 of two.

  6. the move: add the doublings

    the line:
    S=2k−1S = 2^k - 1
    where does this come from?
    question 1 of the page doubling and halving sumsAdd 1+2+4+⋯+2n1 + 2 + 4 + \dots + 2^n. What is the total?
    1. the move: name the sum

      the line:
      S=1+2+4+⋯+2nS = 1 + 2 + 4 + \dots + 2^n

      why it is allowed: Let SS be the doubling sum up to 2n2^n. For nn as 3, it is 1 + 2 + 4 + 8.

    2. the move: double both sides

      the line:
      2S=2+4+8+⋯+2n+12S = 2 + 4 + 8 + \dots + 2^{n + 1}

      why it is allowed: Each term doubled is the next one along, and 2n2^n becomes 2n+12^{n + 1}. Doubling both sides keeps them equal. The plan: the two sums share all but their ends.

    3. the move: take line 1 away

      the line:
      2S−S=(2+4+⋯+2n+1)−(1+2+⋯+2n)\begin{aligned} 2S - S = {} & (2 + 4 + \dots + 2^{n + 1}) \\ & - (1 + 2 + \dots + 2^n) \end{aligned}

      why it is allowed: Take SS from both sides of line 2. On the right, write SS out as line 1 does.

    4. the move: tidy the left side

      the line:
      S=(2+4+⋯+2n+1)−(1+2+⋯+2n)\begin{aligned} S = {} & (2 + 4 + \dots + 2^{n + 1}) \\ & - (1 + 2 + \dots + 2^n) \end{aligned}

      why it is allowed: Two lots of SS less one lot is one lot.

    5. the move: cancel what both brackets share

      the line:
      S=2n+1−1S = 2^{n + 1} - 1
      when n is 3124816
      first bracket24816
      second bracket1248
      left overtake away 116
      Line 4 when nn is 3. The 2, 4 and 8 cancel, leaving 16 less 1, which is 15.

      why it is allowed: Every term from 2 to 2n2^n is in both brackets and cancels, leaving 2n+12^{n + 1} less 1.

    6. the move: the terms before the last

      the line:
      1+2+⋯+2n−1=2(n−1)+1−1\begin{gathered} 1 + 2 + \dots + 2^{n - 1} \\ = 2^{(n - 1) + 1} - 1 \end{gathered}

      why it is allowed: The sum of line 5 stopping one term sooner: line 5 with n−1n - 1 for nn. For 3, it is 1 + 2 + 4. At nn as 0 no terms are left, adding to 0, and 2 to the power 0, less 1, is 0 too.

    7. the move: tidy the power

      the line:
      2(n−1)+1−1=2n−12^{(n - 1) + 1} - 1 = 2^n - 1

      why it is allowed: One more than n−1n - 1 is nn. For 3, 1 + 2 + 4 is 7, one less than 8.

    8. the move: read it

      the line:
      one less thanthe next term,under twice the last\begin{gathered} \text{one less than} \\ \text{the next term,} \\ \text{under twice the last} \end{gathered}

      why it is allowed: By lines 6 and 7, the terms before the last add to one less than it: the last outweighs them all. By line 5 the sum is under 2n+12^{n + 1}, twice the last.

    the whole page: doubling and halving sums

    why it is allowed: The box under this line adds them. For 4 numbers, 1 + 2 + 4 is 7, one less than 8.

  7. the move: put k in

    the line:
    S=2⌊log⁡2 n!⌋−1−1S = 2^{\lfloor \log_2\, n! \rfloor - 1} - 1

    why it is allowed: By line 3.

  8. the move: halve the power

    the line:
    S=2⌊log⁡2 n!⌋2−1S = \frac{2^{\lfloor \log_2\, n! \rfloor}}{2} - 1
    where does this come from?
    question 2 of the page halving and logarithmsHalve nn, rounding down each time. How many halvings reach 1?
    1. the move: name the log rounded down

      the line:
      K=⌊log⁡2 n⌋K = \lfloor \log_2\, n \rfloor
      numberlog× 2+ 14283164113.46352.322211100
      Rounding down, 11 halves to 5, 2 and 1. In blue, each log rounded down: 3, 2, 1, 0, one less at each halving.

      why it is allowed: Here nn is the number halved, from 2 up; for 11, KK is 3.

    2. the move: rounding down never adds

      the line:
      ⌊log⁡2 n⌋≤log⁡2 n\lfloor \log_2\, n \rfloor \le \log_2\, n

      why it is allowed: For 11, 3 is at most 3.46.

    3. the move: rounding down takes off less than 1

      the line:
       log⁡2 n<⌊log⁡2 n⌋+1\begin{gathered} \,\log_2\, n \\ < \lfloor \log_2\, n \rfloor + 1 \end{gathered}

      why it is allowed: For 11, 4 is above 3.46.

    4. the move: raise 2 to each side of line 2

      the line:
      2⌊log⁡2 n⌋≤2log⁡2 n2^{\lfloor \log_2\, n \rfloor} \le 2^{\log_2\, n}

      why it is allowed: 2 raised to a bigger power gives a bigger number. For 11, 8 is at most about 11.

    5. the move: 2 to the log of n is n

      the line:
      2⌊log⁡2 n⌋≤n2^{\lfloor \log_2\, n \rfloor} \le n

      why it is allowed: By what a log is. For 11, 8 is at most 11.

    6. the move: raise 2 to each side of line 3

      the line:
      2log⁡2 n<2⌊log⁡2 n⌋+12^{\log_2\, n} < 2^{\lfloor \log_2\, n \rfloor + 1}

      why it is allowed: As in line 4. For 11, about 11 is below 16.

    7. the move: 2 to the log of n is n

      the line:
      n<2⌊log⁡2 n⌋+1n < 2^{\lfloor \log_2\, n \rfloor + 1}

      why it is allowed: As in line 5. For 11, 11 is below 16.

    8. the move: halve both sides of line 5

      the line:
      2⌊log⁡2 n⌋/2≤n/22^{\lfloor \log_2\, n \rfloor} / 2 \le n / 2

      why it is allowed: For 11, 4 is at most 5.5, which is not whole.

    9. the move: write the half as a power

      the line:
      2⌊log⁡2 n⌋−1≤n/22^{\lfloor \log_2\, n \rfloor - 1} \le n / 2

      why it is allowed: Half a power of 2 has one 2 fewer. Half of 8 is 4.

    10. the move: round the half down

      the line:
      2⌊log⁡2 n⌋−1≤⌊n/2⌋2^{\lfloor \log_2\, n \rfloor - 1} \le \lfloor n / 2 \rfloor

      why it is allowed: ⌊n/2⌋\lfloor n / 2 \rfloor is the half rounded down, 5 for 11. A whole number at most 5.5 is at most 5. The left side, 4 for 11, is whole, as KK is at least 1 for nn from 2 up.

    11. the move: halve both sides of line 7

      the line:
      n/2<2⌊log⁡2 n⌋+1/2n / 2 < 2^{\lfloor \log_2\, n \rfloor + 1} / 2

      why it is allowed: For 11, 5.5 is below 8.

    12. the move: write the half as a power

      the line:
      n/2<2⌊log⁡2 n⌋n / 2 < 2^{\lfloor \log_2\, n \rfloor}

      why it is allowed: As in line 9. Half of 16 is 8.

    13. the move: round the half down

      the line:
      ⌊n/2⌋<2⌊log⁡2 n⌋\lfloor n / 2 \rfloor < 2^{\lfloor \log_2\, n \rfloor}

      why it is allowed: Rounding down never adds. For 11, 5 is below 8.

    14. the move: take the log of line 10

      the line:
       log⁡2 2⌊log⁡2 n⌋−1≤log⁡2 ⌊n/2⌋\begin{gathered} \,\log_2\, 2^{\lfloor \log_2\, n \rfloor - 1} \\ \le \log_2\, \lfloor n / 2 \rfloor \end{gathered}

      why it is allowed: A bigger number has a bigger log. For 11, the log of 4 is at most the log of 5.

    15. the move: the log of a power of 2 is the power

      the line:
      ⌊log⁡2 n⌋−1≤log⁡2 ⌊n/2⌋\begin{gathered} \lfloor \log_2\, n \rfloor - 1 \\ \le \log_2\, \lfloor n / 2 \rfloor \end{gathered}

      why it is allowed: For 11, the log of 4 is 2, at most about 2.32.

    16. the move: take the log of line 13

      the line:
       log⁡2 ⌊n/2⌋<log⁡2 2⌊log⁡2 n⌋\begin{gathered} \,\log_2\, \lfloor n / 2 \rfloor \\ < \log_2\, 2^{\lfloor \log_2\, n \rfloor} \end{gathered}

      why it is allowed: As in line 14. For 11, the log of 5 is below the log of 8.

    17. the move: the log of a power of 2 is the power

      the line:
       log⁡2 ⌊n/2⌋<⌊log⁡2 n⌋\begin{gathered} \,\log_2\, \lfloor n / 2 \rfloor \\ < \lfloor \log_2\, n \rfloor \end{gathered}

      why it is allowed: For 11, about 2.32 is below 3.

    18. the move: round the log down

      the line:
      ⌊log⁡2 ⌊n/2⌋⌋=⌊log⁡2 n⌋−1\begin{gathered} \lfloor \log_2\, \lfloor n / 2 \rfloor \rfloor \\ = \lfloor \log_2\, n \rfloor - 1 \end{gathered}
      the numberat leastbelowits log rounded down
      118163
      5482
      2241
      1120
      Each halving takes 1 off the log rounded down.

      why it is allowed: By lines 15 and 17, the log of the half is at least one less than KK and below KK, so it rounds down to one less. For 11, about 2.32 rounds down to 2.

    19. the move: use line 18 again and again

      the line:
      after K halvings,rounding down,the log roundeddown is 0\begin{gathered} \text{after } K \text{ halvings,} \\ \text{rounding down,} \\ \text{the log rounded} \\ \text{down is 0} \end{gathered}

      why it is allowed: While the log rounded down is 1 or more, the number is at least 2 to the power 1, which is 2. So line 18 takes 1 off each halving, down to 0 after KK. For 11, 3, 2, 1, 0.

    20. the move: a log rounded down to 0 belongs to 1

      the line:
      K halvings,rounding down,bring n to 1\begin{gathered} K \text{ halvings,} \\ \text{rounding down,} \\ \text{bring } n \text{ to 1} \end{gathered}

      why it is allowed: Such a log is at least 0 and below 1, so its number is at least 1 and below 2. It is 1.

    the whole page: halving and logarithms

    why it is allowed: One 2 fewer in a power halves it. The box under this line does the same, at its lines 8 and 9.

  9. the move: under half of n!

    the line:
    S≤n!2−1S \le \frac{n!}{2} - 1
    numbersn!n!kkSShalf of n!n! less 1
    4243711
    512053159
    67208255359
    The short lists against half the orders, less 1, for 4, 5 and 6 numbers.

    why it is allowed: The box at line 8 shows 2 to the power of (the log rounded down, less 1) is at most half the number, at its line 9. At 4, 8 is at most 12, so 7 is at most 11.

  10. the move: fewer than half are quick

    the line:
    fewer than half the ordersfinish in fewer than k\begin{gathered} \text{fewer than half the orders} \\ \text{finish in fewer than } k \end{gathered}

    why it is allowed: By lines 2 and 9, as there are n!n! orders. For 4 numbers, at most 7 of 24.

try it with a small nn: at n=4n = 4, line 4 gives S=7S = 7, which you can work out by hand

Why does a shuffled row cost Θ(n log⁡2 n)\Theta(n \,\log_2\, n) comparisons on average?
  1. the move: most orders are slow

    the line:
    more than half the orderstake at least k comparisons\begin{gathered} \text{more than half the orders} \\ \text{take at least } k \text{ comparisons} \end{gathered}

    why it is allowed: By the question on short lists. For 4 numbers, at least 17 of 24 take 3 or more.

  2. the move: add up the slow ones

    the line:
    the comparisons over every orderadd up to more than n!2×k\begin{gathered} \text{the comparisons over every order} \\ \text{add up to more than } \frac{n!}{2} \times k \end{gathered}

    why it is allowed: By line 1, more than half the n!n! orders add at least kk each, and no order adds less than 0. For 4 numbers, at least 17 times 3, which is 51.

  3. the move: a floor for the average

    the line:
    A≥k2A \ge \frac{k}{2}
    numberskkhalf of kkaverage
    431.56.5
    552.510.95
    68415.13
    7115.519.79
    814725.81
    Heap sort's average over every order, against half of k. The floor is low, but the next lines show it grows like the average.

    why it is allowed: AA is that total shared out over the n!n! orders, so by line 2 it is more than half of kk. For 4 numbers, 51 over 24 is above 1.5.

  4. the move: drop the rounding

    the line:
    A≥log⁡2 n!−22A \ge \frac{\log_2\, n! - 2}{2}

    why it is allowed: Rounding down takes off less than 1, so kk is at least the log of n!n! less 2.

  5. the move: use the sorting floor's growth

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

    why it is allowed: From 4 on, the log of n!n! is at least a quarter of n log⁡2 nn \,\log_2\, n. The box at line 6 of the question on the dearest row shows it, at its line 17.

  6. the move: halve each part

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

    why it is allowed: Half of a quarter is an eighth, and half of 2 is 1.

  7. the move: a simpler floor

    the line:
    A≥n log⁡2 n16 for n≥7A \ge \frac{n \,\log_2\, n}{16} \text{ for } n \ge 7

    why it is allowed: From 7 on, n log⁡2 nn \,\log_2\, n is at least 16, so taking 1 off its eighth leaves at least its sixteenth. At 7 it is about 19.65; its eighth less 1 is about 1.46, its sixteenth about 1.23.

  8. 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 7, the fixed multiple a sixteenth, from 7 on.

  9. the move: a ceiling from every row

    the line:
    A≤2⌊log⁡2 n⌋(⌊n/2⌋+n−2)A \le 2 \lfloor \log_2\, n \rfloor (\lfloor n / 2 \rfloor + n - 2)

    why it is allowed: No row goes past UU, by the question on the ceiling, so neither does the average.

  10. 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: The question on the ceiling finds UU under 3 times n log⁡2 nn \,\log_2\, n.

  11. the move: ceiling and floor together

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

    why it is allowed: Lines 8 and 10 bound AA by the same growth, n log⁡2 nn \,\log_2\, n.

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

count it yourself

Count every comparison on 2, 2, 2, 2. For 4 numbers the formula gives 3 times 4, less 6, which is 6.

2, 2, 2, 2, every step written down
stepthe rowwhat happenscomparisonsswaps
12, 2, 2, 2There are 4 numbers in a row, drawn below as a tree: the number in place p has its children in places 2p and 2p + 1.2, 2, 2, 200
22, 2, 2, 2Sift 2 down: while a child is bigger, swap it with its bigger child.2, 2, 2, 200
32, 2, 2, 22 is not bigger than 2.2, 2, 2, 210
42, 2, 2, 22 is at least as big as its children, so it stops here.2, 2, 2, 210
52, 2, 2, 2Sift 2 down: while a child is bigger, swap it with its bigger child.2, 2, 2, 210
62, 2, 2, 22 is not bigger than 2.2, 2, 2, 220
72, 2, 2, 22 is not bigger than 2.2, 2, 2, 230
82, 2, 2, 22 is at least as big as its children, so it stops here.2, 2, 2, 230
92, 2, 2, 2Every number is now at least as big as its children, so the biggest, 2, is at the top.2, 2, 2, 230
102, 2, 2, 2Swap the top, 2, the biggest left, to the end of the heap, where it stays for good.2, 2, 2, 231
112, 2, 2, 2The heap is one smaller. Sift the new top, 2, down.2, 2, 2, 231
122, 2, 2, 22 is not bigger than 2.2, 2, 2, 241
132, 2, 2, 22 is not bigger than 2.2, 2, 2, 251
142, 2, 2, 22 is at least as big as its children, so it stops here.2, 2, 2, 251
152, 2, 2, 2Swap the top, 2, the biggest left, to the end of the heap, where it stays for good.2, 2, 2, 252
162, 2, 2, 2The heap is one smaller. Sift the new top, 2, down.2, 2, 2, 252
172, 2, 2, 22 is not bigger than 2.2, 2, 2, 262
182, 2, 2, 22 is at least as big as its children, so it stops here.2, 2, 2, 262
192, 2, 2, 2Swap the top, 2, the biggest left, to the end of the heap, where it stays for good.2, 2, 2, 263
202, 2, 2, 2Only 2 is left in the heap, so it is in place too.2, 2, 2, 263
212, 2, 2, 2In order, after 6 comparisons and 3 swaps.2, 2, 2, 263

In all, 6 comparisons. The formula from section 4, 3n−63n - 6, gives B=6B = 6 at n=4n = 4: the same.

where you meet it

Heap sort is the safety net inside a fast standard sort.

  • the C++ library's sort

    C++ comes with a library, ready made code for common jobs. In the one that comes with the GNU compiler, std::sort splits like quick sort. It picks a number and splits the part into numbers no bigger and numbers no smaller. When its parts go more than twice a heap's height deep, it heap sorts the part. For two million numbers the height is 20, so the limit is 40. So no row makes it slow.

    source: the GNU C++ library's bits/stl_algo.h (__sort, __introsort_loop, __partial_sort, __heap_select) and bits/stl_algobase.h (__lg), GCC 15.2.0 as packaged in libstdc++-15-dev 15.2.0-16ubuntu1, read offline

  • the C++ library's heap tools

    The same library offers heap sort's two halves. std::make_heap builds a heap, and std::sort_heap moves the top to the end and mends the heap, again and again. std::partial_sort uses a heap to find the smallest few numbers in order.

    source: the GNU C++ library's bits/stl_heap.h (make_heap, sort_heap, __pop_heap, __adjust_heap) and bits/stl_algo.h (partial_sort, __heap_select), GCC 15.2.0, read offline

what is used instead

Heap sort is rarely the first choice. Sebastian Bourges' books, Algorithmic Thinking Without the Jargon, volume two, chapter 24, find it the slowest in practice of three fast sorts: merge sort, quick sort and heap sort. It also lets equal numbers swap. Sorting 5, 5, 1 ends 1, 5, 5 with the second 5 first and the first 5 last. Merge sort keeps them in order. The books put the pairing well: 'Quicksort supplies the speed, heapsort supplies the guarantee, and the combination has both.' (volume two, chapter 24)

how it compares

Heap sort beside the other ways to put a row in order. Its nearest rivals are merge sort, which needs a second row, and quick sort, which is slow on a row already in order.

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 sortmerge sortheap sort10110210310410510610710810910101011101210131014101102103104105106107bubble sortcocktail shaker sortinsertion sortselection sortshell sortquick sortrandomised quick sortmerge sortheap 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