Binary 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 has its children at places and , 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.
step 11 of 40
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
step 14 of 40
Swap them: 5 climbs above 12.
what it remembers to know where it is
- doing operation
- 4
- moving
- 5
- in the heap
- 4
step 20 of 40
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
step 21 of 40
12 is smaller than 23.
what it remembers to know where it is
- doing operation
- 6
- moving
- 23
- in the heap
- 4
step 23 of 40
Swap them: 23 sinks below 12.
what it remembers to know where it is
- doing operation
- 6
- moving
- 23
- in the heap
- 4
step 25 of 40
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
the steps, in plain words
choose a step to mark the Python, a programming language, that does it
- start with an empty heap: a row read as a tree, smallest on topPython line 8
- to put a number in, add it at the end of the rowPython lines 10 and 11
- while it is smaller than the number above it, swap themPython lines 12, 13, 14, 15, 16, 17 and 18
- to take one out, take the smallest, from the topPython line 19
- move the last number to the topPython lines 20, 21 and 22
- 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
- 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 (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
, 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
| comparisons | time | |
|---|---|---|
| 1,000 | 2,994 | about 3 microseconds |
| 100,000 | 299,994 | about 300 microseconds |
| 10,000,000 | 29,999,994 | about 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 . 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.
| bestevery number the same, the cheapest | averagedifferent numbers put in shuffled, then all taken out; the average over every order, each as likely | |
|---|---|---|
| comparisons | , from 3 numbers on | from 3 numbers on, between and ; at 8, between 18 and 72 |
| how the comparisons grow in each case | ||
| tight, | ||
| ceiling, | ||
| floor, | ||
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.
| numbers | all equal | cheapest | average | dearest | biggest first |
|---|---|---|---|---|---|
| 4 | 6 | 6 | 6.67 | 7 | 7 |
| 5 | 9 | 9 | 10.93 | 12 | 12 |
| 6 | 12 | 12 | 15.4 | 18 | 16 |
| 7 | 15 | 16 | 20.11 | 24 | 21 |
| 8 | 18 | 21 | 26.54 | 31 | 28 |
| numbers | per put | per take | |
|---|---|---|---|
| 10 | 1.4 | 2.6 | 3.3 |
| 100 | 2.1 | 8.5 | 6.6 |
| 1,000 | 2.2 | 15.0 | 10.0 |
| 10,000 | 2.3 | 21.7 | 13.3 |
step 16 of 20
Put 40 at the end of the row, in place 7.
comparisons: 0
step 18 of 20
Swap them: 40 climbs above 47.
comparisons: 1
step 19 of 20
40 is not smaller than 12, the number above it, so it stays.
comparisons: 2
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.
the move: count the puts
the line:operation then held comparisons put 4 1 0 put 4, four times more 5 4 take 4 2 take 3 2 take 2 1 take 1 0 take 0 0 in all 9 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 comparisons; 4 for 5 numbers.
the move: count the takes
the line:step 14 of 18
4 is out. Move the last number, 4, to the top.
comparisons: 0
step 15 of 18
4 is not smaller than 4.
comparisons: 1
step 16 of 18
4 is not smaller than 4.
comparisons: 2
step 17 of 18
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 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.
guess it, thenthe move: add them
the line:why it is allowed: is the comparisons on equal numbers. By line 1, for the puts; by line 2, 2 for each of the takes that leave 3 or more, and 1 for the take that leaves 2. Takes leaving 1 or none compare nothing.
guess it, thenthe move: multiply out
the line:why it is allowed: Twice is .
guess it, thenthe move: gather
the line:why it is allowed: The 1s cancel. For 5 numbers, 4 + 4 + 1 is 9, as in the picture.
guess it, thenthe move: nothing costs fewer
the line: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.
guess it, thenthe move: a ceiling
the line:why it is allowed: By line 5, taking 6 away.
guess it, thenthe move: read it as a bound
the line:why it is allowed: By line 7, stays under 3 times .
guess it, thenthe move: a floor
the line:why it is allowed: is plus , and is at least 0 from 3 on. At 5, 9 is 5 + 4.
guess it, thenthe move: read it as a bound
the line:why it is allowed: By line 9.
guess it, thenthe move: ceiling and floor together
the line:why it is allowed: Lines 8 and 10 bound by the same growth, .
guess it, then
try it with a small : at , line 3 gives , which you can work out by hand
the move: a put starts at the end
the line: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 counts the numbers with it.
the move: one comparison a level
the line:step 8 of 14
Put 5 at the end of the row, in place 4.
comparisons: 0
step 10 of 14
Swap them: 5 climbs above 31.
comparisons: 1
step 12 of 14
Swap them: 5 climbs above 12.
comparisons: 2
step 13 of 14
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.
guess it, thenthe move: biggest first climbs all the way
the line:put starts at place levels to the top comparisons 96 1 0 0 81 2 1 1 70 3 1 1 54 4 2 2 39 5 2 2 17 6 2 2 in all 8 Biggest first. Each climbs to the top, one comparison a level, 8 in all. why it is allowed: 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.
guess it, thenthe move: name the levels
the line:where does this come from?
question 3 of the page trees and their wordsA tree of places kept in a row. What is its height? the move: the last place is the deepest
the line:why it is allowed: The row fills the levels in order, so its last place, place , is on the last level. So the height is the depth of place .
the move: each step up halves
the line: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 is place . From place 10 the steps up go 5, 2, 1.
the move: count the steps
the line:why it is allowed: Let be the height. By lines 1 and 2 it is the steps from place up to place 1, each one halving, rounding down.
the move: use halving and logarithms
the line:where does this come from?
question 2 of the page halving and logarithmsHalve , rounding down each time. How many halvings reach 1? the move: name the log rounded down
the line: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 is the number halved, from 2 up; for 11, is 3.
the move: rounding down never adds
the line:why it is allowed: For 11, 3 is at most 3.46.
the move: rounding down takes off less than 1
the line:why it is allowed: For 11, 4 is above 3.46.
the move: raise 2 to each side of line 2
the line:why it is allowed: 2 raised to a bigger power gives a bigger number. For 11, 8 is at most about 11.
the move: 2 to the log of n is n
the line:why it is allowed: By what a log is. For 11, 8 is at most 11.
the move: raise 2 to each side of line 3
the line:why it is allowed: As in line 4. For 11, about 11 is below 16.
the move: 2 to the log of n is n
the line:why it is allowed: As in line 5. For 11, 11 is below 16.
the move: halve both sides of line 5
the line:why it is allowed: For 11, 4 is at most 5.5, which is not whole.
the move: write the half as a power
the line:why it is allowed: Half a power of 2 has one 2 fewer. Half of 8 is 4.
the move: round the half down
the line:why it is allowed: 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 is at least 1 for from 2 up.
the move: halve both sides of line 7
the line:why it is allowed: For 11, 5.5 is below 8.
the move: write the half as a power
the line:why it is allowed: As in line 9. Half of 16 is 8.
the move: round the half down
the line:why it is allowed: Rounding down never adds. For 11, 5 is below 8.
the move: take the log of line 10
the line:why it is allowed: A bigger number has a bigger log. For 11, the log of 4 is at most the log of 5.
the move: the log of a power of 2 is the power
the line:why it is allowed: For 11, the log of 4 is 2, at most about 2.32.
the move: take the log of line 13
the line:why it is allowed: As in line 14. For 11, the log of 5 is below the log of 8.
the move: the log of a power of 2 is the power
the line:why it is allowed: For 11, about 2.32 is below 3.
the move: round the log down
the line:the number at least below its log rounded down 11 8 16 3 5 4 8 2 2 2 4 1 1 1 2 0 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 and below , so it rounds down to one less. For 11, about 2.32 rounds down to 2.
the move: use line 18 again and again
the line: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 . For 11, 3, 2, 1, 0.
the move: a log rounded down to 0 belongs to 1
the line: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.
why it is allowed: The page on halving shows that halving , rounding down, reaches 1 after 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.
the move: read it
the line: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.
why it is allowed: The box under this line shows that the last place of a tree of places lies levels below the top. For 6 numbers, 1 + 1 + 2 + 2 + 2 is 8, as in the picture.
guess it, thenthe move: no puts climb more
the line:step 8 of 12
Put 20 at the end of the row, in place 4.
comparisons: 0
step 10 of 12
Swap them: 20 climbs above 31.
comparisons: 1
step 11 of 12
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 lies 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.
guess it, thenthe move: add up the puts
the line:why it is allowed: Line 5 for each put, from = 2 to , adds up to line 4's sum, which is .
guess it, thenthe move: a ceiling
the line:why it is allowed: Line 4 has terms, each at most the last, . For 6, 8 is at most 5 times 2.
guess it, thenthe move: drop the rounding
the line:why it is allowed: Rounding down makes no bigger.
guess it, thenthe move: round up to
the line:why it is allowed: is less than .
guess it, thenthe move: read it as a bound
the line:why it is allowed: By line 9, with the fixed multiple 1.
guess it, then
try it with a small : at , line 3 gives , which you can work out by hand
the move: the last moves up
the line:why it is allowed: The top, the smallest, goes. The last number takes its place, so the row keeps no gap. Here counts the numbers left.
the move: price a round
the line:step 18 of 26
14 is out. Move the last number, 71, to the top.
comparisons: 0
step 21 of 26
Swap them: 71 sinks below 27.
comparisons: 2
step 24 of 26
Swap them: 71 sinks below 46.
comparisons: 4
step 25 of 26
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. round compares then 1 27 with 71, 35 with 27 swap 71 with 27 2 46 with 71, 52 with 46 swap 71 with 46 no round no child below 71 it stays Each round of that take, in comparisons. Two rounds of 2, then no round. why it is allowed: Place 's children are and , 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.
guess it, thenthe move: count the rounds
the line: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.
guess it, thenthe move: price the rounds
the line:why it is allowed: By line 2, a round compares at most the 2 children. In the picture, 2 rounds make 4.
guess it, thenthe move: add up the takes
the line: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 leaving height line 4 allows the most it makes 4 2 4 3 3 1 2 2 2 1 2 1 1 0 0 0 in all 8 6 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: adds up line 4 for the takes leaving down to 1, so the takes compare at most . The take leaving none compares nothing.
guess it, thenthe move: name the heights
the line:where does this come from?
question 3 of the page trees and their wordsA tree of places kept in a row. What is its height? the move: the last place is the deepest
the line:why it is allowed: The row fills the levels in order, so its last place, place , is on the last level. So the height is the depth of place .
the move: each step up halves
the line: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 is place . From place 10 the steps up go 5, 2, 1.
the move: count the steps
the line:why it is allowed: Let be the height. By lines 1 and 2 it is the steps from place up to place 1, each one halving, rounding down.
the move: use halving and logarithms
the line:where does this come from?
question 2 of the page halving and logarithmsHalve , rounding down each time. How many halvings reach 1? the move: name the log rounded down
the line: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 is the number halved, from 2 up; for 11, is 3.
the move: rounding down never adds
the line:why it is allowed: For 11, 3 is at most 3.46.
the move: rounding down takes off less than 1
the line:why it is allowed: For 11, 4 is above 3.46.
the move: raise 2 to each side of line 2
the line:why it is allowed: 2 raised to a bigger power gives a bigger number. For 11, 8 is at most about 11.
the move: 2 to the log of n is n
the line:why it is allowed: By what a log is. For 11, 8 is at most 11.
the move: raise 2 to each side of line 3
the line:why it is allowed: As in line 4. For 11, about 11 is below 16.
the move: 2 to the log of n is n
the line:why it is allowed: As in line 5. For 11, 11 is below 16.
the move: halve both sides of line 5
the line:why it is allowed: For 11, 4 is at most 5.5, which is not whole.
the move: write the half as a power
the line:why it is allowed: Half a power of 2 has one 2 fewer. Half of 8 is 4.
the move: round the half down
the line:why it is allowed: 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 is at least 1 for from 2 up.
the move: halve both sides of line 7
the line:why it is allowed: For 11, 5.5 is below 8.
the move: write the half as a power
the line:why it is allowed: As in line 9. Half of 16 is 8.
the move: round the half down
the line:why it is allowed: Rounding down never adds. For 11, 5 is below 8.
the move: take the log of line 10
the line:why it is allowed: A bigger number has a bigger log. For 11, the log of 4 is at most the log of 5.
the move: the log of a power of 2 is the power
the line:why it is allowed: For 11, the log of 4 is 2, at most about 2.32.
the move: take the log of line 13
the line:why it is allowed: As in line 14. For 11, the log of 5 is below the log of 8.
the move: the log of a power of 2 is the power
the line:why it is allowed: For 11, about 2.32 is below 3.
the move: round the log down
the line:the number at least below its log rounded down 11 8 16 3 5 4 8 2 2 2 4 1 1 1 2 0 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 and below , so it rounds down to one less. For 11, about 2.32 rounds down to 2.
the move: use line 18 again and again
the line: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 . For 11, 3, 2, 1, 0.
the move: a log rounded down to 0 belongs to 1
the line: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.
why it is allowed: The page on halving shows that halving , rounding down, reaches 1 after 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.
the move: read it
the line: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.
why it is allowed: The box under this line shows a heap of numbers is high. For 5, 2 times (0 + 1 + 1 + 2) is 8.
guess it, thenthe move: one take
the line:why it is allowed: One term of line 6. For 6 left, twice 2 is 4.
guess it, thenthe move: a ceiling
the line:why it is allowed: Line 6 has terms, each at most twice , as a smaller heap is no taller.
guess it, thenthe move: drop the rounding
the line:why it is allowed: Rounding down makes no bigger.
guess it, thenthe move: round up to
the line:why it is allowed: is less than .
guess it, thenthe move: read it as a bound
the line:why it is allowed: By line 10, with the fixed multiple 2.
guess it, then
try it with a small : at , line 5 gives , which you can work out by hand
the move: the takes sort
the line:why it is allowed: Put 1 to 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.
the move: one list each
the line: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.
guess it, thenthe move: choose k
the line:why it is allowed: Less 2, so the quick orders stay under half, as line 8 shows. From 3 numbers on, 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 is 3. The box at line 7 shows the floor is .
guess it, thenthe move: count the short lists
the line:why it is allowed: is the lists of fewer than answers.
guess it, thenthe move: lists of each length
the line:where does this come from?
question 2 of the page the sorting floorHow many different lists of yes-or-no answers are there? the move: two answers
the line:why it is allowed: Here counts answers, not numbers. Each comparison answers yes or no.
the move: each answer doubles
the line:answers the lists how many 0 the empty list 1 1 yes; no 2 2 yes yes; yes no; no yes; no no 4 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.
the move: double n times
the line:why it is allowed: Let be the number of lists of answers. By line 2, 1 doubled times. For 3, 2 × 2 × 2 is 8.
the move: a power
the line:why it is allowed: 2s multiplied are written , read 2 to the power . 2 to the power 0 is 1.
the move: read it
the line:why it is allowed: By line 4, one answer more is one 2 more: 4 answers make 16 lists and 5 make 32.
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.
guess it, thenthe move: add the doublings
the line:where does this come from?
question 1 of the page doubling and halving sumsAdd . What is the total? the move: name the sum
the line:why it is allowed: Let be the doubling sum up to . For as 3, it is 1 + 2 + 4 + 8.
the move: double both sides
the line:why it is allowed: Each term doubled is the next one along, and becomes . Doubling both sides keeps them equal. The plan: the two sums share all but their ends.
the move: take line 1 away
the line:why it is allowed: Take from both sides of line 2. On the right, write out as line 1 does.
the move: tidy the left side
the line:why it is allowed: Two lots of less one lot is one lot.
the move: cancel what both brackets share
the line:when n is 3 1 2 4 8 16 first bracket 2 4 8 16 second bracket 1 2 4 8 left over take away 1 16 Line 4 when is 3. The 2, 4 and 8 cancel, leaving 16 less 1, which is 15. why it is allowed: Every term from 2 to is in both brackets and cancels, leaving less 1.
the move: the terms before the last
the line:why it is allowed: The sum of line 5 stopping one term sooner: line 5 with for . For 3, it is 1 + 2 + 4. At as 0 no terms are left, adding to 0, and 2 to the power 0, less 1, is 0 too.
the move: tidy the power
the line:why it is allowed: One more than is . For 3, 1 + 2 + 4 is 7, one less than 8.
the move: read it
the line: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 , twice the last.
why it is allowed: The box under this line adds them. For 4 numbers, 1 + 2 + 4 is 7, one less than 8.
guess it, thenthe move: put k in
the line: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 different numbers take? the move: answers decide
the line:the row answers moves it ends as 1, 3, 2 no yes no swap the last two 1, 2, 3 10, 30, 20 no yes no swap the last two 10, 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.
the move: one list per order
the line: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.
the move: fill out short lists
the line: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 be the most comparisons on any order. Fill each shorter list out to 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.
the move: count both
the line:orders the floor its lists 3 6 3 8 4 24 5 32 5 120 7 128 8 40,320 16 65,536 12 479,001,600 29 536,870,912 One answer fewer gives half the lists, too few. why it is allowed: Each answer doubles the lists, so answers make , against 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.
the move: name the floor
the line:why it is allowed: Let be the fewest doublings of 1 that reach or pass it. For 4, four doublings reach only 16, short of 24, and the fifth, 32, passes it.
the move: at least
the line:why it is allowed: By line 4, doublings of 1 reach , and by line 5 no fewer than do. So is at least .
the move: halving and logarithms
the line:where does this come from?
question 4 of the page halving and logarithmsHalve , rounding up each time. How many halvings reach 1? the move: name the log rounded up
the line:why it is allowed: Here is the number halved, from 2 up. For 11, is 4.
the move: rounding up never takes off
the line:why it is allowed: The bracket is . For 11, 3.46 is at most 4.
the move: rounding up adds less than 1
the line:why it is allowed: For 11, 3 is below 3.46.
the move: raise 2 to each side of line 2
the line:why it is allowed: As in line 4 of question 2 of the page halving and logarithms.
the move: 2 to the log of n is n
the line:why it is allowed: As in line 5 of question 2 of the page halving and logarithms. For 11, 11 is at most 16.
the move: raise 2 to each side of line 3
the line:why it is allowed: As in line 4.
the move: 2 to the log of n is n
the line:why it is allowed: As in line 5. For 11, 8 is below 11.
the move: halve both sides of line 5
the line:why it is allowed: Halving both sides keeps it true.
the move: write the half as a power
the line: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.
the move: round the half up
the line:why it is allowed: 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 is at least 1. By line 9 it is at or above the half, so no smaller than the half rounded up.
the move: halve both sides of line 7
the line:why it is allowed: Halving both sides keeps it true.
the move: write the half as a power
the line: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, is 1, so this is 2 to the power minus 1, one half, as drawn.
the move: round the half up
the line:why it is allowed: Rounding up never takes off. For 11, 4 is below 6.
the move: take the log of line 10
the line:why it is allowed: As in line 14 of question 2 of the page halving and logarithms.
the move: the log of a power of 2 is the power
the line:why it is allowed: For 11, the log of 6, about 2.58, is at most 3.
the move: take the log of line 13
the line: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.
the move: the log of a power of 2 is the power
the line:why it is allowed: For 11, 2 is below about 2.58.
the move: round the log up
the line:the number above at most its log rounded up 11 8 16 4 6 4 8 3 3 2 4 2 2 1 2 1 1 1/2 1 0 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 and at most one less, so it rounds up to one less. For 11, about 2.58 rounds up to 3.
the move: use line 18 again and again
the line: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 halvings. For 11, 4, 3, 2, 1, 0.
the move: a log rounded up to 0 belongs to 1
the line:why it is allowed: Such a log is at most 0, so its number is at most 1, and so is 1.
the move: read lines 5 and 7 as doublings
the line:why it is allowed: Doubling 1 gives the powers of 2. By line 5, doublings get to or past ; by line 7, one fewer stay below. For 11, 8 stays below and 16 gets past.
the move: count merge sort's rounds
the line:Round 2 merges 5, 9 and 2, 7 into 2, 5, 7, 9. after round runs start 11 1 6 2 3 3 2 4 1 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 after rounds, not fewer.
the move: read it
the line: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.
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.
the move: read it
the line:why it is allowed: By lines 6 and 7, every comparing sort that makes no random choices makes at least comparisons on its worst row of . 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).
why it is allowed: By line 3. The box under this line finds the sorting floor, the fewest doublings of 1 that reach .
guess it, thenthe move: under half of n!
the line: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. numbers half of less 1 4 24 3 7 11 5 120 5 31 59 6 720 8 255 359 7 5,040 11 2,047 2,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 . Line 7's power is one doubling fewer again, so it falls short of half of . At 4, 8 is short of 12, so 7 is at most 11.
guess it, thenthe move: fewer than half are quick
the line:why it is allowed: By lines 2 and 8, as there are orders. For 4 numbers, at most 7 of 24.
guess it, then
try it with a small : at , line 4 gives , which you can work out by hand
the move: most orders are slow
the line:why it is allowed: By the question on short lists. For 4 numbers, at least 17 of 24 take 3 or more.
the move: add up the slow ones
the line:orders of 4 how many comparisons each quick at most 7 fewer than 3 slow at least 17 3 or more all 24 together 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 orders add at least each, and none adds less than 0. For 4 numbers, at least 17 times 3, which is 51.
guess it, thenthe move: a floor for the average
the line:numbers half of average 4 3 1.5 6.67 5 5 2.5 10.93 6 8 4 15.4 7 11 5.5 20.11 8 14 7 26.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: is that total shared out over the orders, so by line 2 it is more than half of . For 4 numbers, 51 over 24 is above 1.5.
guess it, thenthe move: drop the rounding
the line:why it is allowed: is the sorting floor less 2, by line 3 of the question on short lists. Rounding up makes no smaller, so is at least .
guess it, thenthe move: write the log as a sum
the line:where does this come from?
question 4 of the page the sorting floorHow does grow? the move: name the log
the line:why it is allowed: Let be the log to base 2 of , for from 4 as lines 12 and 15 need. For 8, about 15.30.
the move: factors at most n
the line:why it is allowed: multiplies whole numbers, each at most . Putting for each gives , read to the power , no smaller. For 8, 40,320 against 16,777,216.
the move: bigger number, bigger log
the line: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.
the move: into line 1
the line:why it is allowed: By line 3, as is the log of .
the move: log of a power
the line: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. is a product of factors, each , so its log is times .
the move: keep the top half
the line:why it is allowed: Drop the factors 1 to half of rounded down; each is at least 1, so the product gets no bigger. Half of rounded down and rounded up add up to , as 3 and 4 for 7. So are kept, read half of rounded up.
the move: half of n for each
the line:for 8 multiplied 8 down to 1 40,320 8 × 7 × 6 × 5 1,680 4 × 4 × 4 × 4 256 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 , so putting half of for each gives no bigger product.
the move: bigger number, bigger log
the line:why it is allowed: As in line 3.
the move: into line 1
the line:why it is allowed: By line 8, as is the log of .
the move: log of a power
the line:why it is allowed: As in line 5. For 8, 4 times 2.
the move: rounding up
the line:why it is allowed: Rounding up makes no smaller, as 3.5 goes up to 4.
the move: log of half of n
the line:why it is allowed: From 4 on, half of is at least 2, whose log is 1; by line 3, bigger numbers have bigger logs.
the move: drop the rounding
the line:why it is allowed: By line 11, half of is at most , as 3.5 against 4 for 7. Each multiplies the log of half of , above zero by line 12, so putting half of in line 10 makes it no bigger.
the move: halving takes 1 off
the line:why it is allowed: is 2 times half of , and the log of 2 is 1. So by line 5 the log of half of is . For 8, the log of 4 is 3 less 1.
the move: a fact about n
the line:why it is allowed: From 4 on, 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.
the move: the smaller part
the line:why it is allowed: By line 15, putting half of for in line 14 makes it no bigger, as in line 13. For 8, 4 times 1.5, 6.
the move: multiply out
the line:- the log of
- a quarter of
The log of between the other two, from 1 to 10 numbers. At 8: 24, about 15.30, and 6. why it is allowed: Half of times half of .
the move: a ceiling
the line:why it is allowed: , read is in big O of , says a fixed multiple of it is a ceiling of . By line 5, 1 times it, from 4 on.
the move: a floor
the line:why it is allowed: , read big omega, says a fixed multiple, above zero, is a floor of , a floor on growth, not the sorting floor. By line 17, a quarter, from 4 on.
the move: both
the line:why it is allowed: , read big theta, says both, by lines 18 and 19. grows like .
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.
guess it, thenthe move: the sum's growth
the line:why it is allowed: The box at line 5 shows the sum is at least a quarter of from 4 on, at its line 17.
guess it, thenthe move: halve each part
the line:why it is allowed: Half of a quarter is an eighth, and half of 2 is 1.
guess it, thenthe move: a simpler floor
the line:why it is allowed: From 7 on, 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.
guess it, thenthe move: read it as a bound
the line:why it is allowed: By line 8, the fixed multiple a sixteenth, from 7 on.
guess it, thenthe move: a ceiling from every order
the line:why it is allowed: No puts compare more than , by the question on climbing. No takes compare more than , by the question on sinking. So no order costs more, nor does the average.
guess it, thenthe move: add them
the line:why it is allowed: One and two times make three times it. At 8, 3 times 24 is 72.
guess it, thenthe move: read it as a bound
the line:why it is allowed: By line 11, the fixed multiple 3.
guess it, thenthe move: ceiling and floor together
the line:why it is allowed: Lines 9 and 12 bound by the same growth, .
guess it, then
try it on small rows: over every order of 7 numbers, the average is about 20.11
the move: an unsorted row
the line: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.
the move: add up the takes
the line:why it is allowed: is the comparisons of an unsorted row. The first take finds other numbers to compare with, and each take after it one fewer, down to none.
guess it, thenthe move: add them
the line:where does this come from?
question 1 of the page what a structure promisesA priority queue kept as an unsorted row. Put in numbers, then take them all out. How many comparisons? the move: one take
the line:row before the take smallest comparisons 5, 2, 8, 3 2 3 5, 8, 3 3 2 5, 8 5 1 8 8 0 in all 6 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 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.
the move: add the takes, the last first
the line:why it is allowed: Let be the comparisons. Puts make none: each number goes at the end. By line 1 the first take, from all numbers, makes , 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.
the move: leave out the 0
the line:why it is allowed: Adding 0 changes nothing.
the move: use the page on adding up
the line:where does this come from?
question 1 of the page adding up Fit two staircases of squares together. What shape do they make? the move: draw the sum as a staircase
the line:why it is allowed: Let be the sum of the whole numbers from 1 to . Draw it as a staircase, a column for each number: 1 square, then 2, and so on up to . For 5, columns of 1, 2, 3, 4 and 5 hold 15 squares.
the move: take two staircases
the line:why it is allowed: Two staircases hold twice the squares. Doubling both sides of line 1 keeps it true.
the move: fit them into a rectangle
the line: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 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 , and the columns fill a rectangle wide and tall.
the move: halve both sides
the line:why it is allowed: Halving both sides of line 3 keeps it true and leaves one . For 5, half of 30 is 15.
why it is allowed: The page on adding up 1 to 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 .
the move: tidy the bracket
the line:numbers stack steps unsorted row comparisons 10 20 45 100 200 4,950 1,000 2,000 499,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: is . The table sets it beside a stack, which compares nothing; its work is 1 step a put and 1 a take.
the move: read it
the line: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.
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.
guess it, thenthe move: a row kept in order
the line: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 numbers, each smaller than all before it, such as 8, 5, 3, 2. How many comparisons? the move: one put
the line:put row after comparisons 8 8 0 5 5, 8 1 3 3, 5, 8 2 2 2, 3, 5, 8 3 in all 6 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.
the move: add the puts
the line:why it is allowed: Let 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.
the move: the same sum as question 1
the line:put row after comparisons 5 5 0 2 2, 5 1 8 2, 5, 8 1 3 2, 3, 5, 8 3 in all 5 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.
the move: read it
the line: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.
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.
guess it, then
try it with a small : at , line 2 gives , 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.
| step | the row | what happens | comparisons | swaps |
|---|---|---|---|---|
| 1 | Start with an empty heap, and 10 operations to do. | 0 | 0 | |
| 2 | 7 | Put 7 at the end of the row, in place 1.7 | 0 | 0 |
| 3 | 7 | 7 is at the top, so it stays.7 | 0 | 0 |
| 4 | 7, 7 | Put 7 at the end of the row, in place 2.7, 7 | 0 | 0 |
| 5 | 7, 7 | 7 is not smaller than 7, the number above it, so it stays.7, 7 | 1 | 0 |
| 6 | 7, 7, 7 | Put 7 at the end of the row, in place 3.7, 7, 7 | 1 | 0 |
| 7 | 7, 7, 7 | 7 is not smaller than 7, the number above it, so it stays.7, 7, 7 | 2 | 0 |
| 8 | 7, 7, 7, 7 | Put 7 at the end of the row, in place 4.7, 7, 7, 7 | 2 | 0 |
| 9 | 7, 7, 7, 7 | 7 is not smaller than 7, the number above it, so it stays.7, 7, 7, 7 | 3 | 0 |
| 10 | 7, 7, 7, 7, 7 | Put 7 at the end of the row, in place 5.7, 7, 7, 7, 7 | 3 | 0 |
| 11 | 7, 7, 7, 7, 7 | 7 is not smaller than 7, the number above it, so it stays.7, 7, 7, 7, 7 | 4 | 0 |
| 12 | 7, 7, 7, 7, 7 | The smallest number is on top, 7.7, 7, 7, 7, 7 | 4 | 0 |
| 13 | 7, 7, 7, 7, 7 | Take 7 out of the top.7, 7, 7, 7, 7 | 4 | 0 |
| 14 | 7, 7, 7, 7 | 7 is out. Move the last number, 7, to the top.7, 7, 7, 7 | 4 | 0 |
| 15 | 7, 7, 7, 7 | 7 is not smaller than 7.7, 7, 7, 7 | 5 | 0 |
| 16 | 7, 7, 7, 7 | 7 is not smaller than 7.7, 7, 7, 7 | 6 | 0 |
| 17 | 7, 7, 7, 7 | 7 is no bigger than the numbers below it, so it stays.7, 7, 7, 7 | 6 | 0 |
| 18 | 7, 7, 7, 7 | The smallest number is on top, 7.7, 7, 7, 7 | 6 | 0 |
| 19 | 7, 7, 7, 7 | Take 7 out of the top.7, 7, 7, 7 | 6 | 0 |
| 20 | 7, 7, 7 | 7 is out. Move the last number, 7, to the top.7, 7, 7 | 6 | 0 |
| 21 | 7, 7, 7 | 7 is not smaller than 7.7, 7, 7 | 7 | 0 |
| 22 | 7, 7, 7 | 7 is not smaller than 7.7, 7, 7 | 8 | 0 |
| 23 | 7, 7, 7 | 7 is no bigger than the numbers below it, so it stays.7, 7, 7 | 8 | 0 |
| 24 | 7, 7, 7 | The smallest number is on top, 7.7, 7, 7 | 8 | 0 |
| 25 | 7, 7, 7 | Take 7 out of the top.7, 7, 7 | 8 | 0 |
| 26 | 7, 7 | 7 is out. Move the last number, 7, to the top.7, 7 | 8 | 0 |
| 27 | 7, 7 | 7 is not smaller than 7.7, 7 | 9 | 0 |
| 28 | 7, 7 | 7 is no bigger than the numbers below it, so it stays.7, 7 | 9 | 0 |
| 29 | 7, 7 | The smallest number is on top, 7.7, 7 | 9 | 0 |
| 30 | 7, 7 | Take 7 out of the top.7, 7 | 9 | 0 |
| 31 | 7 | 7 is out. Move the last number, 7, to the top.7 | 9 | 0 |
| 32 | 7 | Nothing is below 7, so it stays.7 | 9 | 0 |
| 33 | 7 | The smallest number is on top, 7.7 | 9 | 0 |
| 34 | 7 | Take 7 out of the top.7 | 9 | 0 |
| 35 | 7 is out, and the heap is empty. | 9 | 0 | |
| 36 | Done. The heap holds nothing. | 9 | 0 |
In all, 9 comparisons. The formula from section 4, , gives at : 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 numbers in, then takes them all out.
| way | a put | a take | all in then all out | reach for it when |
|---|---|---|---|---|
| an unsorted row | no comparison | one fewer than it holds | , in every order | takes are rare |
| a row kept in order | up to one for each number it holds | no comparison | up to | you need them in order too |
| a binary heap | up to , about 2.2 on average at 1,000 numbers | up to | from up to | puts and takes come mixed |
- the plain rows,
- a heap at most,
- a heap at least,