Skip to content

Binary heap

storing

Level 2 of 3

Also called Priority queue and Min-heap.

how it works

However the numbers arrive, a heap keeps the smallest ready to take.

Numbers keep arriving, and again and again you take out the smallest. That promise is called a priority queue, and a binary heap is one way to keep it. It holds the numbers in a row, read as a tree: place pp has its children at places 2p2p and 2p+12p + 1, so place 2's children are places 4 and 5. No number sits under a bigger one, so the smallest is on top. A put adds a number at the end of the row. While it is smaller than the number above it, the two swap: it climbs. A take takes the top out and moves the last number to the top. While a number below it is smaller, it swaps with the smaller of them: it sinks. Flip every comparison and the biggest is on top instead, as in heap sort's learn page. Sebastian Bourges' books, volume two, chapter 23, call the two a min-heap and a max-heap. The storyboard below puts in 31, 12, 47, 5 and 23, the operations numbered 1 to 5, then takes one, operation 6. Each place's letter is the order its number came in.

122311475012131247354
31, 12 and 47 are in, 12 having climbed above 31. 5 is put at place 4, the small numbers counting its steps up. It is smaller than 31, then 12, so it climbs twice, to the top.
depth01251247312351122473314235012
After 31, 12, 47, 5 and 23 are put in. 5 is on top, over 12 and 47, and 12 is over 31 and 23. No number sits under a bigger one. Each level's depth is marked, 0 at the top.
depth01247233151247123231354125012
Every comparison flipped. Now the biggest, 47, is on top, and no number sits over a bigger one.
Putting in and taking out: 6 moments of its 40 steps, the steps between them left for the watch page
  1. step 11 of 40

    123451231475b12a31c47d5

    5 is smaller than 31, the number above it.

    what it remembers to know where it is
    doing operation
    4
    moving
    5
    in the heap
    4

    watch from here

  2. step 14 of 40

    123455124731d5b12c47a31

    Swap them: 5 climbs above 12.

    what it remembers to know where it is
    doing operation
    4
    moving
    5
    in the heap
    4

    watch from here

  3. step 20 of 40

    1234523124731e23b12c47a31

    5 is out. Move the last number, 23, to the top.

    what it remembers to know where it is
    doing operation
    6
    moving
    23
    in the heap
    4

    watch from here

  4. step 21 of 40

    1234523124731e23b12c47a31

    12 is smaller than 23.

    what it remembers to know where it is
    doing operation
    6
    moving
    23
    in the heap
    4

    watch from here

  5. step 23 of 40

    1234512234731b12e23c47a31

    Swap them: 23 sinks below 12.

    what it remembers to know where it is
    doing operation
    6
    moving
    23
    in the heap
    4

    watch from here

  6. step 25 of 40

    1234512234731b12e23c47a31

    23 is no bigger than the numbers below it, so it stays.

    what it remembers to know where it is
    doing operation
    6
    moving
    23
    in the heap
    4

    watch from here

the steps, in plain words
  1. start with an empty heap: a row read as a tree, smallest on topPython line 8
  2. to put a number in, add it at the end of the rowPython lines 10 and 11
  3. while it is smaller than the number above it, swap themPython lines 12, 13, 14, 15, 16, 17 and 18
  4. to take one out, take the smallest, from the topPython line 19
  5. move the last number to the topPython lines 20, 21 and 22
  6. while a number below it is smaller, swap it with the smaller of themPython lines 23, 24, 25, 26, 27, 28, 29, 30, 31 and 32
  7. an empty heap has nothing to takePython lines 19 and 33
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 binary_heap(operations):
    """Run a list of operations on a heap kept in a row, smallest on top.

    A number puts it in, and None takes the smallest out. Read the row as a
    tree: Python counts places from 0, so place p has its children at 2p + 1
    and 2p + 2, and the place above it is (p - 1) // 2. Returns the row.
    """
    heap = []  # an empty heap
    for op in operations:
        if op is not None:  # put a number in
            heap.append(op)  # at the end of the row
            place = len(heap) - 1
            while place > 0:  # the top has nothing above it
                above = (place - 1) // 2
                if op >= heap[above]:  # not smaller: it stays
                    break
                heap[place], heap[above] = heap[above], heap[place]  # climb
                place = above
        elif heap:  # take the smallest out, from the top
            last = heap.pop()  # the last number leaves the end
            if heap:  # unless it was the only one,
                heap[0] = last  # it goes to the top, over the smallest
                place = 0
                while True:
                    small = place  # the smallest so far: the number itself
                    for child in (2 * place + 1, 2 * place + 2):
                        if child < len(heap) and heap[child] < heap[small]:
                            small = child
                    if small == place:  # no number below it is smaller
                        break
                    heap[place], heap[small] = heap[small], heap[place]  # sink
                    place = small
        # an empty heap has nothing to take, so None does nothing
    return heap

how it scales

How the comparisons grow, from ten numbers to a million, each put in and then taken out.

Each step across or up is ten times the one before, a log-log plot. From 3 numbers on, equal numbers cost 3n−63n - 6 (section 4 counts it; 5 equal numbers cost 9). Their line climbs about one step up for each step across: ten times the numbers, about ten times the comparisons. Shuffled numbers climb more: ten times the numbers always costs more than ten times the comparisons. It is about 26 times from 10 to 100 numbers and about 12 times from 100,000 to a million. The extra is the log, which grows slowly.

comparisons, ten times more at each mark up

slope 1102104106108101102103104105106107slope 1101102103104105106107108101102103104105106107slope 1101102103104105106107108101102103104105106107

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

  • different numbers put in shuffled, then all taken out; the average over every order, each 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 cheapestsolid 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 a binary heap's comparisons yourself, as the plot on this page does.

Run it with Python 3.12 or later. For each size n it puts n numbers into an
empty heap and takes them all out, and prints the comparisons for n numbers
all the same, the cheapest, and the average over 20 shuffles of 1 to n. 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 __lt__(self, other):
        Counted.comparisons += 1
        return self.value < other.value

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


def binary_heap(operations):
    """Run a list of operations on a heap kept in a row, smallest on top.

    A number puts it in, and None takes the smallest out. Read the row as a
    tree: Python counts places from 0, so place p has its children at 2p + 1
    and 2p + 2, and the place above it is (p - 1) // 2. Returns the row.
    """
    heap = []  # an empty heap
    for op in operations:
        if op is not None:  # put a number in
            heap.append(op)  # at the end of the row
            place = len(heap) - 1
            while place > 0:  # the top has nothing above it
                above = (place - 1) // 2
                if op >= heap[above]:  # not smaller: it stays
                    break
                heap[place], heap[above] = heap[above], heap[place]  # climb
                place = above
        elif heap:  # take the smallest out, from the top
            last = heap.pop()  # the last number leaves the end
            if heap:  # unless it was the only one,
                heap[0] = last  # it goes to the top, over the smallest
                place = 0
                while True:
                    small = place  # the smallest so far: the number itself
                    for child in (2 * place + 1, 2 * place + 2):
                        if child < len(heap) and heap[child] < heap[small]:
                            small = child
                    if small == place:  # no number below it is smaller
                        break
                    heap[place], heap[small] = heap[small], heap[place]  # sink
                    place = small
        # an empty heap has nothing to take, so None does nothing
    return heap


def cheapest(n):
    """n numbers all the same, put in, then n takes: nothing climbs or sinks."""
    return [1] * n + [None] * n


def count(operations):
    """How many comparisons the heap makes on this list of operations."""
    Counted.comparisons = 0
    binary_heap([None if op is None else Counted(op) for op in operations])
    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 + [None] * n))
        print(f"{n:>6} {count(cheapest(n)):>13} {sum(shuffles) / 20:>10.1f}")

best, worst and average

The numbers decide the cost. Equal numbers are the cheapest: no put climbs and no take sinks. Shuffled numbers cost more. Their average is measured, and section 4 shows it grows like n log⁡2 nn \,\log_2\, n. The grid below has no worst column. The table below shows biggest first is dearest only up to 5 numbers; at 6, 7 and 8 other orders cost more. So section 4 caps every order from above instead.

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 cheapestaveragedifferent numbers put in shuffled, then all taken out; the average over every order, each as likely
comparisons3n−63n - 6, from 3 numbers onfrom 3 numbers on, between 3n−63n - 6 and 3n log⁡2 n3n \,\log_2\, n; at 8, between 18 and 72
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 beside the row that holds the numbers

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

numbersall equalcheapestaveragedearestbiggest first
4666.6777
59910.931212
6121215.41816
7151620.112421
8182126.543128
In comparisons, all in then all out; the orders use 1 to n. Equal numbers always cost the least. Biggest first is a dearest order up to 5, but not at 6, 7 or 8.
numbersper putper takelog⁡2 n\log_2\, n
101.42.63.3
1002.18.56.6
1,0002.215.010.0
10,0002.321.713.3
Comparisons for each put and each take, on average over 20 shuffles of 1 to n. From 100 numbers on, a put costs about the same at every size. From 1,000 to 10,000 numbers the log grows by 3.3, and a take by 6.7, twice as much.
  1. step 16 of 20

    12234731526840

    Put 40 at the end of the row, in place 7.

    comparisons: 0

  2. step 18 of 20

    12234031526847

    Swap them: 40 climbs above 47.

    comparisons: 1

  3. step 19 of 20

    12234031526847

    40 is not smaller than 12, the number above it, so it stays.

    comparisons: 2

40 put into a heap of 6 climbs above 47 and stops under 12. 2 comparisons, about a shuffled put's average.

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, from 3 on, cost exactly 3n−63n - 6 comparisons, the fewest any nn numbers can?
  1. the move: count the puts

    the line:
    each put after the firstcompares once, then stays\begin{gathered} \text{each put after the first} \\ \text{compares once, then stays} \end{gathered}
    operationthen heldcomparisons
    put 410
    put 4, four times more54
    take42
    take32
    take21
    take10
    take00
    in all9
    Five 4s in, then all out. The puts make 4 comparisons and the takes 5.

    why it is allowed: An equal number is not smaller than the one above it, so it stays where it is put. So n−1n - 1 comparisons; 4 for 5 numbers.

  2. the move: count the takes

    the line:
    a take leaving 3 or morecompares 2; one leaving 2compares 1\begin{gathered} \text{a take leaving 3 or more} \\ \text{compares 2; one leaving 2} \\ \text{compares 1} \end{gathered}
    1. step 14 of 18

      4444

      4 is out. Move the last number, 4, to the top.

      comparisons: 0

    2. step 15 of 18

      4444

      4 is not smaller than 4.

      comparisons: 1

    3. step 16 of 18

      4444

      4 is not smaller than 4.

      comparisons: 2

    4. step 17 of 18

      4444

      4 is no bigger than the numbers below it, so it stays.

      comparisons: 2

    One take from five 4s. The last 4 moves to the top, meets both children, no smaller, and stays. 2 comparisons.

    why it is allowed: The last number moves to the top and meets the top's children, no smaller, so it stays. A heap of 3 or more has 2 children under the top, and a heap of 2 has 1. From 3 numbers on, there are n−3n - 3 takes that leave 3 or more, 2 comparisons each, and one take that leaves 2. For 5, the takes leave 4, 3, 2, 1 and 0, and two of them leave 3 or more.

  3. 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 line 1, n−1n - 1 for the puts; by line 2, 2 for each of the n−3n - 3 takes that leave 3 or more, and 1 for the take that leaves 2. Takes leaving 1 or none compare nothing.

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

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

  6. the move: nothing costs fewer

    the line:
    any n numbers compareat least this\begin{gathered} \text{any } n \text{ numbers compare} \\ \text{at least this} \end{gathered}

    why it is allowed: On any numbers, a put into a heap that is not empty compares at least once. A take compares each child of the top at least once. Lines 1 and 2 count only those.

  7. the move: a ceiling

    the line:
    B≤3nB \le 3n

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

  8. the move: read it as a bound

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

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

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

  10. the move: read it as a bound

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

    why it is allowed: By line 9.

  11. the move: ceiling and floor together

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

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

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

At most how many comparisons can nn puts make, and which puts make that many?
  1. the move: a put starts at the end

    the line:
    a put into a heap that thenholds m starts at place m\begin{gathered} \text{a put into a heap that then} \\ \text{holds } m \text{ starts at place } m \end{gathered}
    122314560123456
    A put making 6 starts at place 6 and climbs through place 3 to place 1, two levels.

    why it is allowed: The new number goes at the end of the row. Here mm counts the numbers with it.

  2. the move: one comparison a level

    the line:
    each comparison climbs a levelor ends the climb\begin{gathered} \text{each comparison climbs a level} \\ \text{or ends the climb} \end{gathered}
    1. step 8 of 14

      1231475

      Put 5 at the end of the row, in place 4.

      comparisons: 0

    2. step 10 of 14

      1254731

      Swap them: 5 climbs above 31.

      comparisons: 1

    3. step 12 of 14

      5124731

      Swap them: 5 climbs above 12.

      comparisons: 2

    4. step 13 of 14

      5124731

      5 is at the top, so it stays.

      comparisons: 2

    5 put into 12, 31, 47. It starts at place 4, climbs above 31, then above 12, and stops at the top. 2 comparisons in all.

    why it is allowed: The number is compared with the one above it. If smaller, they swap and it climbs a level; if not, it stays. At the top it compares nothing.

  3. the move: biggest first climbs all the way

    the line:
    C=levels from place 2 to the top+⋯+levels from place n\begin{gathered} C = \text{levels from place 2 to the top} \\ + \dots + \text{levels from place } n \end{gathered}
    putstarts at placelevels to the topcomparisons
    96100
    81211
    70311
    54422
    39522
    17622
    in all8
    Biggest first. Each climbs to the top, one comparison a level, 8 in all.

    why it is allowed: CC is the comparisons the puts make when the numbers come biggest first. Each is then smaller than all before it, so it climbs to the top, one comparison a level, by line 2.

  4. the move: name the levels

    the line:
    C=⌊log⁡2 2⌋+⌊log⁡2 3⌋+⋯+⌊log⁡2 n⌋\begin{gathered} C = \lfloor \log_2\, 2 \rfloor + \lfloor \log_2\, 3 \rfloor \\ + \dots + \lfloor \log_2\, n \rfloor \end{gathered}
    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 under this line shows that the last place of a tree of mm places lies ⌊log⁡2 m⌋\lfloor \log_2\, m \rfloor levels below the top. For 6 numbers, 1 + 1 + 2 + 2 + 2 is 8, as in the picture.

  5. the move: no puts climb more

    the line:
    a put making m comparesat most ⌊log⁡2 m⌋ times\begin{gathered} \text{a put making } m \text{ compares} \\ \text{at most } \lfloor \log_2\, m \rfloor \text{ times} \end{gathered}
    1. step 8 of 12

      12314720

      Put 20 at the end of the row, in place 4.

      comparisons: 0

    2. step 10 of 12

      12204731

      Swap them: 20 climbs above 31.

      comparisons: 1

    3. step 11 of 12

      12204731

      20 is not smaller than 12, the number above it, so it stays.

      comparisons: 2

    20 put at place 4, 2 levels down, climbs one level and stops under 12. 2 comparisons, as many as a climb to the top.

    why it is allowed: By line 4, place mm lies ⌊log⁡2 m⌋\lfloor \log_2\, m \rfloor levels down, and by line 2 a climb to the top costs one comparison a level. A climb that stops early costs one more, to stop, but it climbs at least one level fewer. 20 put into 12, 31, 47 compares twice and climbs one level.

  6. the move: add up the puts

    the line:
    so any n puts compareat most C\begin{gathered} \text{so any } n \text{ puts compare} \\ \text{at most } C \end{gathered}

    why it is allowed: Line 5 for each put, from mm = 2 to nn, adds up to line 4's sum, which is CC.

  7. the move: a ceiling

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

    why it is allowed: Line 4 has n−1n - 1 terms, each at most the last, ⌊log⁡2 n⌋\lfloor \log_2\, n \rfloor. For 6, 8 is at most 5 times 2.

  8. the move: drop the rounding

    the line:
    C≤(n−1) log⁡2 nC \le (n - 1) \,\log_2\, n

    why it is allowed: Rounding down makes no bigger.

  9. the move: round n−1n - 1 up to nn

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

    why it is allowed: n−1n - 1 is less than nn.

  10. the move: read it as a bound

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

    why it is allowed: By line 9, with the fixed multiple 1.

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

At most how many comparisons can nn takes make? A ceiling, from 3 numbers on never reached.
  1. the move: the last moves up

    the line:
    a take that leaves s numbersmoves the last to place 1\begin{gathered} \text{a take that leaves } s \text{ numbers} \\ \text{moves the last to place 1} \end{gathered}

    why it is allowed: The top, the smallest, goes. The last number takes its place, so the row keeps no gap. Here ss counts the numbers left.

  2. the move: price a round

    the line:
    a round at place pcompares its children,2p and 2p+1, thenstays or sinks a level\begin{gathered} \text{a round at place } p \\ \text{compares its children,} \\ 2p \text{ and } 2p + 1 \text{, then} \\ \text{stays or sinks a level} \end{gathered}
    1. step 18 of 26

      712735465268

      14 is out. Move the last number, 71, to the top.

      comparisons: 0

    2. step 21 of 26

      277135465268

      Swap them: 71 sinks below 27.

      comparisons: 2

    3. step 24 of 26

      274635715268

      Swap them: 71 sinks below 46.

      comparisons: 4

    4. step 25 of 26

      274635715268

      Nothing is below 71, so it stays.

      comparisons: 4

    One take from 14, 27, 35, 46, 52, 68, 71. 71 moves up and sinks below 27, then 46. 4 comparisons.
    roundcomparesthen
    127 with 71, 35 with 27swap 71 with 27
    246 with 71, 52 with 46swap 71 with 46
    no roundno child below 71it stays
    Each round of that take, in comparisons. Two rounds of 2, then no round.

    why it is allowed: Place pp's children are 2p2p and 2p+12p + 1, as section 1 of the learn page reads the row. Each is compared with the smaller so far, the number itself first. In the picture, 27 with 71, then 35 with 27. The number swaps with a smaller child.

  3. the move: count the rounds

    the line:
    at most as many roundsas the heap is high\begin{gathered} \text{at most as many rounds} \\ \text{as the heap is high} \end{gathered}

    why it is allowed: A round needs a child below, so the last level holds none. In the picture, the heap of 6 is 2 high, and 71 sinks 2 rounds.

  4. the move: price the rounds

    the line:
    at most 2 comparisonsa round, so at mosttwice the height\begin{gathered} \text{at most 2 comparisons} \\ \text{a round, so at most} \\ \text{twice the height} \end{gathered}

    why it is allowed: By line 2, a round compares at most the 2 children. In the picture, 2 rounds make 4.

  5. the move: add up the takes

    the line:
    D=2×the heightof a heap of 1+…+2×that of n−1\begin{gathered} D = 2 \times \text{the height} \\ \text{of a heap of 1} + \dots \\ + 2 \times \text{that of } n - 1 \end{gathered}
    12341234
    In a heap of 4 the top has 2 children, place 2 only 1. So a take leaving 4 makes at most 2 and 1, 3, not line 4's 4.
    a take leavingheightline 4 allowsthe most it makes
    4243
    3122
    2121
    1000
    in all86
    The most each take of 5 makes, over every order of 1 to 5. The take leaving 2 always makes 1 where line 4 allows 2, so from 3 numbers on the ceiling is never reached.

    why it is allowed: DD adds up line 4 for the takes leaving n−1n - 1 down to 1, so the takes compare at most DD. The take leaving none compares nothing.

  6. the move: name the heights

    the line:
    D=2⌊log⁡2 1⌋+…+2⌊log⁡2(n−1)⌋\begin{gathered} D = 2\lfloor \log_2\, 1 \rfloor + \dots \\ + 2\lfloor \log_2 (n - 1) \rfloor \end{gathered}
    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 under this line shows a heap of ss numbers is ⌊log⁡2 s⌋\lfloor \log_2\, s \rfloor high. For 5, 2 times (0 + 1 + 1 + 2) is 8.

  7. the move: one take

    the line:
    so a take leaving scompares at most 2⌊log⁡2 s⌋\begin{gathered} \text{so a take leaving } s \\ \text{compares at most } 2\lfloor \log_2\, s \rfloor \end{gathered}

    why it is allowed: One term of line 6. For 6 left, twice 2 is 4.

  8. the move: a ceiling

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

    why it is allowed: Line 6 has n−1n - 1 terms, each at most twice ⌊log⁡2 n⌋\lfloor \log_2\, n \rfloor, as a smaller heap is no taller.

  9. the move: drop the rounding

    the line:
    D≤2(n−1) log⁡2 nD \le 2(n - 1) \,\log_2\, n

    why it is allowed: Rounding down makes no bigger.

  10. the move: round n−1n - 1 up to nn

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

    why it is allowed: n−1n - 1 is less than nn.

  11. the move: read it as a bound

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

    why it is allowed: By line 10, with the fixed multiple 2.

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

The first half of why the average grows like n log⁡2 nn \,\log_2\, n. For nn different numbers, how many orders can finish in fewer than kk comparisons, kk a number line 3 chooses?
  1. the move: the takes sort

    the line:
    the takes give the numbersback smallest first\begin{gathered} \text{the takes give the numbers} \\ \text{back smallest first} \end{gathered}

    why it is allowed: Put 1 to nn in, in any order, then take them all out. They come out 1, 2, and on. The heap learns about them only by comparing two at a time, so this is a comparing sort.

  2. the move: one list each

    the line:
    each order of 1 to ngets its own list of answers\begin{gathered} \text{each order of 1 to } n \\ \text{gets its own list of answers} \end{gathered}

    why it is allowed: Put in 1 then 2, and the second put's comparison answers no; put in 2 then 1, and it answers yes. Two orders given the same answers get the same swaps, so the takes read the same places in both. Then at most one comes out 1, 2, and on. So each order needs a list of answers of its own. The box at line 7 shows it, at its line 2.

  3. the move: choose k

    the line:
    k is the sorting floor less 2,⌈log⁡2 n!⌉−2\begin{gathered} k \text{ is the sorting floor less 2,} \\ \lceil \log_2\, n! \rceil - 2 \end{gathered}

    why it is allowed: Less 2, so the quick orders stay under half, as line 8 shows. From 3 numbers on, kk is at least 1. For 4 numbers, 24 orders. Four doublings of 1 give 16, short of 24, and five give 32, which reaches it, so the floor is 5 and kk is 3. The box at line 7 shows the floor is ⌈log⁡2 n!⌉\lceil \log_2\, n! \rceil.

  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!⌉−2−1S = 2^{\lceil \log_2\, n! \rceil - 2} - 1
    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: By line 3. The box under this line finds the sorting floor, the fewest doublings of 1 that reach n!n!.

  8. the move: under half of n!

    the line:
    S≤n!2−1S \le \frac{n!}{2} - 1
    numberlog× 2+ 110214216432583123.58244.58
    Doublings of 1. The 24 orders of 4 numbers are first reached by 32. Two doublings fewer, 8, falls short of 12, half of 24.
    numbersn!n!kkSShalf of n!n! less 1
    4243711
    512053159
    67208255359
    75,040112,0472,519
    The short lists against half the orders, less 1, for 4 to 7 numbers.

    why it is allowed: One doubling fewer than the floor falls short of n!n!. Line 7's power is one doubling fewer again, so it falls short of half of n!n!. At 4, 8 is short of 12, so 7 is at most 11.

  9. 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 8, 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 do shuffled numbers 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}
    orders of 4how manycomparisons each
    quickat most 7fewer than 3
    slowat least 173 or more
    all24together at least 51
    Most orders are slow, so the average is at least 51 over 24, about 2.1.

    why it is allowed: By line 1, more than half the n!n! orders add at least kk each, and none 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.67
    552.510.93
    68415.4
    7115.520.11
    814726.54
    The average over every order of 1 to n 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: kk is the sorting floor less 2, by line 3 of the question on short lists. Rounding up makes no smaller, so kk is at least log⁡2 n!−2\log_2\, n! - 2.

  5. the move: write the log as a sum

    the line:
    A≥(log⁡2 1+log⁡2 2+⋯+log⁡2 n)−22A \ge \frac{(\log_2\, 1 + \log_2\, 2 + \dots + \log_2\, n) - 2}{2}
    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 2 × 16 = 32 is 5, which is 1 + 4.

  6. the move: the sum'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: The box at line 5 shows the sum is at least a quarter of n log⁡2 nn \,\log_2\, n from 4 on, at its line 17.

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

  8. 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 1 is at most its sixteenth. Its eighth is two sixteenths, so taking 1 off leaves at least one. At 7, about 19.65, an eighth less 1 is about 1.46, above a sixteenth, about 1.23.

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

  10. the move: a ceiling from every order

    the line:
    A≤n log⁡2 n+2n log⁡2 nA \le n \,\log_2\, n + 2n \,\log_2\, n

    why it is allowed: No nn puts compare more than n log⁡2 nn \,\log_2\, n, by the question on climbing. No nn takes compare more than 2n log⁡2 n2n \,\log_2\, n, by the question on sinking. So no order costs more, nor does the average.

  11. the move: add them

    the line:
    A≤3n log⁡2 nA \le 3n \,\log_2\, n

    why it is allowed: One and two times n log⁡2 nn \,\log_2\, n make three times it. At 8, 3 times 24 is 72.

  12. 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 11, the fixed multiple 3.

  13. 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 9 and 12 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 20.11

What do an unsorted row and a row kept in order cost, putting nn numbers in and taking them all out?
  1. the move: an unsorted row

    the line:
    a take compares its waythrough every number left\begin{gathered} \text{a take compares its way} \\ \text{through every number left} \end{gathered}

    why it is allowed: A put adds the number at the end, with no comparison. A take holds the first number and compares it with each of the others, keeping the smaller.

  2. the move: add up the takes

    the line:
    R=0+1+⋯+(n−1)R = 0 + 1 + \dots + (n - 1)

    why it is allowed: RR is the comparisons of an unsorted row. The first take finds n−1n - 1 other numbers to compare with, and each take after it one fewer, down to none.

  3. the move: add them

    the line:
    R=(n−1)n2R = \frac{(n - 1)n}{2}
    where does this come from?
    question 1 of the page what a structure promisesA priority queue kept as an unsorted row. Put in nn numbers, then take them all out. How many comparisons?
    1. the move: one take

      the line:
      a take from m numbersmakes m−1 comparisons\begin{gathered} \text{a take from } m \text{ numbers} \\ \text{makes } m - 1 \text{ comparisons} \end{gathered}
      row before the takesmallestcomparisons
      5, 2, 8, 323
      5, 8, 332
      5, 851
      880
      in all6
      Taking 5, 2, 8 and 3 out of an unsorted row, smallest first. Each take makes one comparison fewer than the numbers left; 6 in all.

      why it is allowed: Here mm is how many numbers are left. To find the smallest, hold the first number and compare it with each of the others, keeping the smaller. On 5, 2, 8, 3: 5 against 2 keeps 2, then 2 against 8 and 2 against 3 keep 2. That is 3 comparisons, the table's first line.

    2. the move: add the takes, the last first

      the line:
      C=0+1+⋯+(n−1)C = 0 + 1 + \dots + (n - 1)

      why it is allowed: Let CC be the comparisons. Puts make none: each number goes at the end. By line 1 the first take, from all nn numbers, makes n−1n - 1, and each take after it one fewer, down to 0. Any order of adding gives the same total, so they are added from the last take.

    3. the move: leave out the 0

      the line:
      C=1+2+⋯+(n−1)C = 1 + 2 + \dots + (n - 1)

      why it is allowed: Adding 0 changes nothing.

    4. the move: use the page on adding up

      the line:
      C=(n−1)((n−1)+1)2C = \frac{(n - 1)\bigl((n - 1) + 1\bigr)}{2}
      where does this come from?
      question 1 of the page adding up 1+2+⋯+n1 + 2 + \dots + nFit two staircases of squares together. What shape do they make?
      1. the move: draw the sum as a staircase

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

        why it is allowed: Let SS be the sum of the whole numbers from 1 to nn. Draw it as a staircase, a column for each number: 1 square, then 2, and so on up to nn. For 5, columns of 1, 2, 3, 4 and 5 hold 15 squares.

      2. the move: take two staircases

        the line:
        2S=2(1+2+⋯+n)2S = 2(1 + 2 + \dots + n)

        why it is allowed: Two staircases hold twice the squares. Doubling both sides of line 1 keeps it true.

      3. the move: fit them into a rectangle

        the line:
        2S=n(n+1)2S = n(n + 1)
        Blue stands, yellow hangs. Two staircases of 1 to 5 squares fill a rectangle 5 wide and 6 tall, 30 squares. So 1 + 2 + 3 + 4 + 5 is 5 times 6, halved, which is 15.

        why it is allowed: Stand one staircase with its tallest column on the left. Hang the other upside down from the top, its tallest column on the right, as in the picture. The first column holds nn standing and 1 hanging. Each column to the right, the standing one loses a square and the hanging one gains one. So every column holds n+1n + 1, and the nn columns fill a rectangle nn wide and n+1n + 1 tall.

      4. the move: halve both sides

        the line:
        S=n(n+1)2S = \frac{n(n + 1)}{2}

        why it is allowed: Halving both sides of line 3 keeps it true and leaves one SS. For 5, half of 30 is 15.

      the whole page: adding up 1+2+⋯+n1 + 2 + \dots + n

      why it is allowed: The page on adding up 1 to nn shows that a sum up to a last number is that number times one more, halved. So 1 + 2 + 3 is 3 times 4, halved, which is 6. Here the last number is n−1n - 1.

    5. the move: tidy the bracket

      the line:
      C=(n−1)n2C = \frac{(n - 1)n}{2}
      numbersstack stepsunsorted row comparisons
      102045
      1002004,950
      1,0002,000499,500
      Putting in that many numbers, then taking them all out. Ten times the numbers gives ten times the stack's steps, and about a hundred times the row's comparisons.

      why it is allowed: (n−1)+1(n - 1) + 1 is nn. The table sets it beside a stack, which compares nothing; its work is 1 step a put and 1 a take.

    6. the move: read it

      the line:
      every take compares its waythrough every number left\begin{gathered} \text{every take compares its way} \\ \text{through every number left} \end{gathered}

      why it is allowed: By line 1, each take compares the first number left with every other one, so the order the numbers arrive in changes nothing. 1,000 numbers cost 499,500, as line 5's table counts.

    the whole page: what a structure promises

    why it is allowed: The box under this line adds them up, whatever the order the numbers came in. For 4 numbers, 3 + 2 + 1 is 6.

  4. the move: a row kept in order

    the line:
    a row kept in order pays Ron its puts, put in biggest first\begin{gathered} \text{a row kept in order pays } R \\ \text{on its puts, put in biggest first} \end{gathered}
    where does this come from?
    question 2 of the page what a structure promisesA priority queue kept instead as a row in order, smallest first. Put in nn numbers, each smaller than all before it, such as 8, 5, 3, 2. How many comparisons?
    1. the move: one put

      the line:
      a put walks in from the backpast every bigger number\begin{gathered} \text{a put walks in from the back} \\ \text{past every bigger number} \end{gathered}
      putrow aftercomparisons
      880
      55, 81
      33, 5, 82
      22, 3, 5, 83
      in all6
      Putting 8, 5, 3 and 2 into a row kept in order. Each new number passes every number already there; 6 comparisons in all, and the takes then cost none.

      why it is allowed: Only comparisons count here; a take makes none, since the smallest is at the front. A put starts at the back and compares with each number, stepping past it while it is bigger. It stops at the first smaller number, and that comparison counts too. So a put compares at most once with each number there, and a number smaller than all before it compares with every one. No order costs more: this is a dearest order.

    2. the move: add the puts

      the line:
      P=0+1+⋯+(n−1)P = 0 + 1 + \dots + (n - 1)

      why it is allowed: Let PP be the comparisons. By line 1 the first put finds the row empty, and each later put passes one more number than the put before.

    3. the move: the same sum as question 1

      the line:
      P=(n−1)n2P = \frac{(n - 1)n}{2}
      putrow aftercomparisons
      550
      22, 51
      82, 5, 81
      32, 3, 5, 83
      in all5
      Putting 5, 2, 8 and 3 into a row kept in order. 8 stops at 5, and 3 passes 8 and 5, then stops at 2; 5 comparisons in all, less than a dearest order's 6.

      why it is allowed: This is line 2 of question 1 of the page what a structure promises, which lines 3 to 5 there work out. The table puts in another order.

    4. the move: read it

      the line:
      the total of question 1,paid on the puts\begin{gathered} \text{the total of question 1,} \\ \text{paid on the puts} \end{gathered}

      why it is allowed: An unsorted row pays this on the takes, whatever the order. A row in order pays it only in a dearest order, and less in the rest: line 3's 5, 2, 8, 3 costs 5.

    the whole page: what a structure promises

    why it is allowed: The box under this line keeps the row smallest first. A put walks in from the back past every bigger number; a take compares nothing. Biggest first, each put passes every number there.

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

count it yourself

Count every comparison as five 7s go in, then all five come out again. Each dash in the input is a take.

7, 7, 7, 7, 7, -, -, -, -, -, every step written down
stepthe rowwhat happenscomparisonsswaps
1Start with an empty heap, and 10 operations to do.00
27Put 7 at the end of the row, in place 1.700
377 is at the top, so it stays.700
47, 7Put 7 at the end of the row, in place 2.7, 700
57, 77 is not smaller than 7, the number above it, so it stays.7, 710
67, 7, 7Put 7 at the end of the row, in place 3.7, 7, 710
77, 7, 77 is not smaller than 7, the number above it, so it stays.7, 7, 720
87, 7, 7, 7Put 7 at the end of the row, in place 4.7, 7, 7, 720
97, 7, 7, 77 is not smaller than 7, the number above it, so it stays.7, 7, 7, 730
107, 7, 7, 7, 7Put 7 at the end of the row, in place 5.7, 7, 7, 7, 730
117, 7, 7, 7, 77 is not smaller than 7, the number above it, so it stays.7, 7, 7, 7, 740
127, 7, 7, 7, 7The smallest number is on top, 7.7, 7, 7, 7, 740
137, 7, 7, 7, 7Take 7 out of the top.7, 7, 7, 7, 740
147, 7, 7, 77 is out. Move the last number, 7, to the top.7, 7, 7, 740
157, 7, 7, 77 is not smaller than 7.7, 7, 7, 750
167, 7, 7, 77 is not smaller than 7.7, 7, 7, 760
177, 7, 7, 77 is no bigger than the numbers below it, so it stays.7, 7, 7, 760
187, 7, 7, 7The smallest number is on top, 7.7, 7, 7, 760
197, 7, 7, 7Take 7 out of the top.7, 7, 7, 760
207, 7, 77 is out. Move the last number, 7, to the top.7, 7, 760
217, 7, 77 is not smaller than 7.7, 7, 770
227, 7, 77 is not smaller than 7.7, 7, 780
237, 7, 77 is no bigger than the numbers below it, so it stays.7, 7, 780
247, 7, 7The smallest number is on top, 7.7, 7, 780
257, 7, 7Take 7 out of the top.7, 7, 780
267, 77 is out. Move the last number, 7, to the top.7, 780
277, 77 is not smaller than 7.7, 790
287, 77 is no bigger than the numbers below it, so it stays.7, 790
297, 7The smallest number is on top, 7.7, 790
307, 7Take 7 out of the top.7, 790
3177 is out. Move the last number, 7, to the top.790
327Nothing is below 7, so it stays.790
337The smallest number is on top, 7.790
347Take 7 out of the top.790
357 is out, and the heap is empty.90
36Done. The heap holds nothing.90

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

where you meet it

Heaps come ready made with many programming languages.

  • Python's heapq

    Python keeps a heap in a plain list, smallest on top, as here. Its put climbs just as this page's does. Its take walks the gap at the top down to the bottom, comparing only the two children, at most one comparison a level. Then the last number climbs back from there. A note in its code says this cut 1,000 takes on shuffled numbers from about 15,000 comparisons to about 8,700.

    source: CPython's Lib/heapq.py (heappush, heappop and the note above _siftup), Python 3.14.4

  • the C++ library's priority queue

    C++ comes with a priority queue that keeps its numbers in a heap in a row too. Unless you tell it otherwise, it keeps the biggest on top: section 1's heap with the comparison flipped.

    source: the GNU C++ library's bits/stl_queue.h (priority_queue), GCC 15.2.0

what is used instead

A heap answers one question cheaply: which number is the smallest? Sebastian Bourges' books, Algorithmic Thinking Without the Jargon, volume two, chapter 23, name the rival, a balanced search tree. It keeps the numbers in order, finds any of them, and grows with the log as a heap does, but needs more memory. To sort numbers you already hold, use heap sort's one pass, not puts one at a time. In the books' words: 'Do not reach for a heap to sort a list you already have.'

how it compares

The ways to keep numbers with the smallest to hand, side by side. Each puts nn numbers in, then takes them all out.

waya puta takeall in then all outreach for it when
an unsorted rowno comparisonone fewer than it holds(n−1)n2\frac{(n - 1)n}{2}, in every ordertakes are rare
a row kept in orderup to one for each number it holdsno comparisonup to (n−1)n2\frac{(n - 1)n}{2}you need them in order too
a binary heapup to ⌊log⁡2 m⌋\lfloor \log_2\, m \rfloor, about 2.2 on average at 1,000 numbersup to 2⌊log⁡2 s⌋2\lfloor \log_2\, s \rfloorfrom 3n−63n - 6 up to 3n log⁡2 n3n \,\log_2\, nputs and takes come mixed
In comparisons. After a put the heap holds mm numbers; after a take, ss are left.
10210410610810101012101410110210310410510610710110210310410510610710810910101011101210131014101102103104105106107
  • the plain rows, (n−1)n2\frac{(n - 1)n}{2}
  • a heap at most, 3n log⁡2 n3n \,\log_2\, n
  • a heap at least, 3n−63n - 6
All in, then all out, on a log-log plot. The rows climb two steps for each step across, the heap about one. Below 31 numbers the rows sit under the heap's ceiling; from 31 on they rise above it. A heap's average is measured, not drawn here; it lies between its two lines.