Changing a number in a heap
how it works
How a heap changes a number it holds.
A heap keeps numbers in a row, read as a tree, smallest on top. Sometimes a number inside must change, as in section 6's route search table. The heap keeps a note of places, where each number stands, so finding a number costs one read, no comparison. It writes the new number there. If the number got smaller, it climbs; if not, it sinks. Choosing which way compares the new number with the old, 9 with 52, not two numbers in the heap, so the site does not count it. The pictures below make 52 into 9 at operation 7, then 27 into 70.
| finding 52 | what it checks | looks |
|---|---|---|
| with the note | reads 52, place 6 | 0 |
| with no note | places 1 to 6, in turn | 6 |
| number | before | 9 written at 6 | 9 swaps with 40 | 9 swaps with 18 |
|---|---|---|---|---|
| 18 | 1 | 1 | 1 | 3 |
| 27 | 2 | 2 | 2 | 2 |
| 40 | 3 | 3 | 6 | 6 |
| 34 | 4 | 4 | 4 | 4 |
| 61 | 5 | 5 | 5 | 5 |
| 52 | 6 | |||
| 9 | 6 | 3 | 1 |
step 20 of 40
52 stands in place 6. The heap keeps a note of where each number stands, so this is one look and no comparison.
what it remembers to know where it is
- doing operation
- 7
- moving
- 52
- at place
- 6
- in the heap
- 6
step 21 of 40
Change 52 to 9. It got smaller, so it is still no bigger than anything below it, but it may need to climb.
what it remembers to know where it is
- doing operation
- 7
- moving
- 9
- at place
- 6
- in the heap
- 6
step 23 of 40
Swap them: 9 climbs above 40.
what it remembers to know where it is
- doing operation
- 7
- moving
- 9
- at place
- 3
- in the heap
- 6
step 25 of 40
Swap them: 9 climbs above 18.
what it remembers to know where it is
- doing operation
- 7
- moving
- 9
- at place
- 1
- in the heap
- 6
step 28 of 40
Change 27 to 70. It got no smaller, so it is still no smaller than anything above it, but it may need to sink.
what it remembers to know where it is
- doing operation
- 8
- moving
- 70
- at place
- 2
- in the heap
- 6
step 31 of 40
Swap them: 70 sinks below 34.
what it remembers to know where it is
- doing operation
- 8
- moving
- 70
- at place
- 4
- in the heap
- 6
step 32 of 40
Nothing is below 70, so it stays.
what it remembers to know where it is
- doing operation
- 8
- moving
- 70
- at place
- 4
- in the heap
- 6
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 lines 9 and 10
- to put a number in, add it at the end of the rowPython lines 65, 66 and 67
- while it is smaller than the number above it, swap themPython lines 22, 23, 24, 25, 26, 27, 28 and 68
- to take one out, take the smallest, from the topPython lines 42 and 44
- move the last number to the topPython lines 45, 46, 47, 48 and 49
- while a number below it is smaller, swap it with the smaller of themPython lines 30, 31, 32, 33, 34, 35, 36, 37, 38, 39 and 50
- an empty heap has nothing to takePython line 43
- to change a number, look up where it stands and write the new number therePython lines 12, 13, 15, 16, 17, 18, 19, 20, 51, 52, 53, 55, 56, 57 and 58
- if it got smaller, while it is smaller than the number above it, swap themPython lines 59, 60, 61 and 62
- if not, while a number below it is smaller, swap it with the smaller of themPython lines 63 and 64
- a number the heap does not hold has nothing to changePython line 54
the same in Python
The steps in plain words are what to learn. Python is a programming language, and the code below does the same steps, for those who code. Python numbers the places in a list from 0, not 1: the first number is numbers[0], the second numbers[1], and so on.
def heap_change_key(operations):
"""Run a list of operations on a heap kept in a row, smallest on top.
A number puts it in, None takes the smallest out, and a pair [a, b]
changes the number a, where it stands first in the row, to b. Python
counts places from 0: 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
where = {} # the note: each number, and the places that hold it
def note(p): # write down that place p holds its number
where.setdefault(int(heap[p]), set()).add(p)
def swap(p, q): # two places trade numbers, and the note follows
where[int(heap[p])].remove(p)
where[int(heap[q])].remove(q)
heap[p], heap[q] = heap[q], heap[p]
note(p)
note(q)
def climb(p): # up while smaller than the number above
while p > 0: # the top has nothing above it
above = (p - 1) // 2
if heap[p] >= heap[above]: # not smaller: it stays
break
swap(p, above)
p = above
def sink(p): # down while a number below is smaller
while True:
small = p # the smallest so far: the number itself
for child in (2 * p + 1, 2 * p + 2):
if child < len(heap) and heap[child] < heap[small]:
small = child
if small == p: # no number below it is smaller
break
swap(p, small)
p = small
for op in operations:
if op is None: # take the smallest out, from the top
if heap: # an empty heap has nothing to take
where[int(heap[0])].remove(0)
last = heap.pop() # the last number leaves the end
if heap: # unless it was the only one,
where[int(last)].remove(len(heap))
heap[0] = last # it goes to the top
note(0)
sink(0)
elif isinstance(op, list): # change a number already in
old, new = op
places = where.get(int(old)) # one look at the note
if places: # a number not held has nothing to change
p = min(places) # where it stands first in the row
places.remove(p)
heap[p] = new
note(p)
# int() reads the two numbers without a comparison
# counted: the site does not count this choice.
if int(new) < int(old): # it got smaller: it climbs
climb(p)
else: # it got no smaller: it sinks
sink(p)
else: # put a number in, at the end of the row
heap.append(op)
note(len(heap) - 1)
climb(len(heap) - 1)
return heap
how it scales
How the comparisons grow, from ten numbers to a million put in, then as many changes.
The page counts one job: for 4, put 5, 6, 7 and 8 in, 3 comparisons, then make four changes, each making a number the smallest. Each mark on the plot is ten times the last. The cheapest job is the puts' : 99,999 at 100,000 and 999,999 at a million, ten times, slope 1. The dearest grows about 12 times, from 1,699,999 to 19,999,999, by the climbs, at most a change: 3 for 10, 9 for 1,000.
comparisons, ten times more at each mark up
, how many numbers are in the heap, ten times more at each mark to the right
- each change makes the number at the last place the smallestsolid where measured by running it; dashed where its formula carries it on to ten millionslope 1.1: ten times n, 12 times the work
- each change makes a number picked at random the smallest; the average over every picksolid where measured by running it; dashed where its formula carries it on to ten million
- each change makes the top smaller, the same place every timesolid where measured by running it; dashed where its formula carries it on to ten million
| comparisons | time | |
|---|---|---|
| 1,000 | 9,999 | about 10 microseconds |
| 100,000 | 1,699,999 | about 1.7 milliseconds |
| 10,000,000 | 239,999,999 | about 240 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 the comparisons of changing numbers in a heap yourself, as this page's plot does.
Run it with Python 3.12 or later. For each size n it puts n + 1 to 2n into an
empty heap, smallest first, then makes n changes, each making a number held
smaller than every number held. It prints the comparisons when each change
makes the top smaller, the cheapest; when each makes the last place smaller,
the dearest; and the average over 20 jobs whose changes pick their numbers at
random. 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 __index__(self):
# int() reads the number this way, which is no comparison.
return self.value
def heap_change_key(operations):
"""Run a list of operations on a heap kept in a row, smallest on top.
A number puts it in, None takes the smallest out, and a pair [a, b]
changes the number a, where it stands first in the row, to b. Python
counts places from 0: 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
where = {} # the note: each number, and the places that hold it
def note(p): # write down that place p holds its number
where.setdefault(int(heap[p]), set()).add(p)
def swap(p, q): # two places trade numbers, and the note follows
where[int(heap[p])].remove(p)
where[int(heap[q])].remove(q)
heap[p], heap[q] = heap[q], heap[p]
note(p)
note(q)
def climb(p): # up while smaller than the number above
while p > 0: # the top has nothing above it
above = (p - 1) // 2
if heap[p] >= heap[above]: # not smaller: it stays
break
swap(p, above)
p = above
def sink(p): # down while a number below is smaller
while True:
small = p # the smallest so far: the number itself
for child in (2 * p + 1, 2 * p + 2):
if child < len(heap) and heap[child] < heap[small]:
small = child
if small == p: # no number below it is smaller
break
swap(p, small)
p = small
for op in operations:
if op is None: # take the smallest out, from the top
if heap: # an empty heap has nothing to take
where[int(heap[0])].remove(0)
last = heap.pop() # the last number leaves the end
if heap: # unless it was the only one,
where[int(last)].remove(len(heap))
heap[0] = last # it goes to the top
note(0)
sink(0)
elif isinstance(op, list): # change a number already in
old, new = op
places = where.get(int(old)) # one look at the note
if places: # a number not held has nothing to change
p = min(places) # where it stands first in the row
places.remove(p)
heap[p] = new
note(p)
# int() reads the two numbers without a comparison
# counted: the site does not count this choice.
if int(new) < int(old): # it got smaller: it climbs
climb(p)
else: # it got no smaller: it sinks
sink(p)
else: # put a number in, at the end of the row
heap.append(op)
note(len(heap) - 1)
climb(len(heap) - 1)
return heap
def picked(n, choose):
"""The job: n + 1 to 2n put in, then n changes, the k-th making the
number choose(held) picks into n + 1 - k, smaller than every number held."""
held = list(range(n + 1, 2 * n + 1))
operations = list(held)
for k in range(1, n + 1):
i = choose(held)
operations.append([held[i], n + 1 - k])
held[i] = n + 1 - k
return operations
def cheapest(n):
"""Each change makes the top smaller, so nothing climbs."""
return list(range(n + 1, 2 * n + 1)) + [[n + 2 - k, n + 1 - k] for k in range(1, n + 1)]
def dearest(n):
"""Each change makes the number at the last place, place n, the smallest."""
heap = heap_change_key(list(range(n + 1, 2 * n + 1)))
operations = list(heap)
for k in range(1, n + 1):
operations.append([heap[n - 1], n + 1 - k]) # the last place's number
heap = heap_change_key(heap + [[heap[n - 1], n + 1 - k]])
return operations
def count(operations):
"""How many comparisons the heap makes on this list of operations."""
Counted.comparisons = 0
given = []
for op in operations:
if op is None:
given.append(None)
elif isinstance(op, list):
given.append([Counted(x) for x in op])
else:
given.append(Counted(op))
heap_change_key(given)
return Counted.comparisons
if __name__ == "__main__":
random.seed(1)
print(f"{'n':>6} {'cheapest':>9} {'dearest':>9} {'at random':>10}")
for n in [10, 100, 1000]:
jobs = [count(picked(n, lambda held: random.randrange(len(held)))) for _ in range(20)]
print(f"{n:>6} {count(cheapest(n)):>9} {count(dearest(n)):>9} {sum(jobs) / 20:>10.1f}")
best, worst and average
Which number each change picks decides the cost: the best case is the cheapest job, the worst the dearest.
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.
| besteach change makes the top smaller, the same place every time | averageeach change makes a number picked at random the smallest; the average over every pick | worsteach change makes the number at the last place the smallest | |
|---|---|---|---|
| comparisons | , the puts alone | for the puts, plus ; at 4, 3 + 0 + 1 + 1 + 2 = 7 | |
| swaps | 0, nothing climbs | ||
| how the comparisons grow in each case | |||
| tight, | |||
| ceiling, | |||
| floor, | |||
extra memory: a note of places beside the row, one entry a number held
Extra memory is the room it needs on top of the input itself, while it runs.
| numbers | put in | the changes write |
|---|---|---|
| 2 | 3, 4 | 2, 1 |
| 3 | 4, 5, 6 | 3, 2, 1 |
| 4 | 5, 6, 7, 8 | 4, 3, 2, 1 |
| numbers | picks | cheapest | average | dearest |
|---|---|---|---|---|
| 2 | 4 | 1 | 2 | 3 |
| 3 | 27 | 2 | 4 | 5 |
| 4 | 256 | 3 | 7 | 11 |
| 5 | 3,125 | 4 | 10 | 14 |
| 6 | 46,656 | 5 | 13 | 17 |
8 made 4 climbs to the top, 2 comparisons
8 made 7 stops at once, 1 comparison
where the formula comes from
Each count above, in small steps. Each step names the line it uses; each 'where does this come from?' box opens a fact from another page.
the move: count the puts
the line:operation comparisons put 5 0 put 6, 7 and 8 3 5 to 4, at the top 0 4 to 3, 3 to 2, 2 to 1 0 in all 3 The cheapest job of 4. Only the puts compare. why it is allowed: The numbers go in smallest first, so each is bigger than the number above it. For 4, 5 to 8 go in, 3 comparisons.
the move: a change at the top
the line:step 10 of 22
5 stands in place 1. The heap keeps a note of where each number stands, so this is one look and no comparison.
comparisons: 0
step 11 of 22
Change 5 to 4. It got smaller, so it is still no bigger than anything below it, but it may need to climb.
comparisons: 0
step 12 of 22
4 is at the top, so it stays.
comparisons: 0
5 at the top becomes 4 and stays. 0 comparisons. why it is allowed: The note finds it with no comparison. A number made smaller at the top has nothing above it, so it stays.
guess it, thenthe move: add them
the line:why it is allowed: is the comparisons when every change is at the top. By line 1, for the puts; by line 2, none for each of the changes.
guess it, thenthe move: tidy
the line:why it is allowed: For 4, 3, as in the picture.
guess it, thenthe move: nothing costs fewer
the line:why it is allowed: A put into a heap that is not empty compares at least once. Changes add 0 or more.
guess it, thenthe move: a ceiling
the line:why it is allowed: By line 4, taking 1 away.
guess it, thenthe move: read it as a bound
the line:why it is allowed: By line 6, with the fixed multiple 1.
guess it, thenthe move: a floor
the line:why it is allowed: By line 4, as half of is at most from 2 on. At 4, 2 is under 3.
guess it, thenthe move: read it as a bound
the line:why it is allowed: By line 8, with the fixed multiple a half.
guess it, thenthe move: ceiling and floor together
the line:why it is allowed: Lines 6 and 8 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 number made smaller climbs
the line:step 10 of 17
8 stands in place 4. The heap keeps a note of where each number stands, so this is one look and no comparison.
comparisons: 0
step 13 of 17
Swap them: 4 climbs above 6.
comparisons: 1
step 15 of 17
Swap them: 4 climbs above 5.
comparisons: 2
step 16 of 17
4 is at the top, so it stays.
comparisons: 2
8 at place 4 becomes 4 and climbs to the top, 2 comparisons and 2 swaps. why it is allowed: It got smaller, so it is still no bigger than anything below it; only the number above can be bigger. At the top it compares nothing.
the move: made the smallest, it goes to the top
the line:why it is allowed: Each comparison finds it smaller, so each one swaps.
guess it, thenthe move: change the last place each time
the line:8 to 4, 2 comparisons
6 to 3, 2 comparisons
5 to 2, 2 comparisons
4 to 1, 2 comparisons
after the fourth change
The dearest job of 4, the heap before each change. Each climb moves the numbers on its way down a place. why it is allowed: is the comparisons when each change makes the number at the last place the smallest. The puts make , by line 1 of the question on the cheapest job. Each change climbs from place , 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 lies levels below the top. For 4, 3 for the puts + 4 × 2 = 11.
guess it, thenthe move: the changes alone
the line:why it is allowed: By line 4, taking away the puts' . For 4, 8.
guess it, thenthe move: count the swaps
the line:why it is allowed: By line 5, the changes compare that many times. Each comparison of a change swaps, by line 2, and no put does, by line 1 of the question on the cheapest job. For 4, 8.
guess it, thenthe move: no change made smaller costs more
the line:8 made 4 climbs 2 levels, 2 comparisons
60 made 30 climbs 1 level, then stops under 14, 2 comparisons
Two changes at place 4. The early stop pays one comparison for the level it does not climb. Each place of a heap of 7 shows , its levels to the top. why it is allowed: Place is the last place of a heap of places. So by the box under line 4, with for , it lies levels down, no deeper than place . An early stop costs no more; see the pictures.
guess it, thenthe move: no job of changes made smaller costs more
the line:why it is allowed: By line 7, after these puts each change costs at most the last place's climb, which line 4 counts times.
guess it, thenthe move: drop the rounding
the line:why it is allowed: By line 4. Rounding down never makes a number bigger: the log of 5, about 2.32, rounds down to 2.
guess it, thenthe move: put for
the line:why it is allowed: From 2 on, is at least 1, so is less than . At 4, 3 is less than 8.
guess it, thenthe move: add them
the line:why it is allowed: At 4, 2 × 4 × 2 is 16, above 11.
guess it, thenthe move: read it as a bound
the line:why it is allowed: By line 11, with the fixed multiple 2.
guess it, thenthe move: a floor
the line:why it is allowed: By line 5, as the puts cost 0 or more.
guess it, thenthe move: rounding down keeps half
the line:numbers rounded down half 2 1 1 0.5 3 1.58 1 0.79 4 2 2 1 7 2.81 2 1.4 8 3 3 1.5 Rounded down, the log never falls below half of itself from 2 on. why it is allowed: While is below 2, at 2 or 3, it rounds down to 1, at least half of it. From 4 on it is at least 2, so the less than 1 rounding takes off is at most half.
guess it, thenthe move: read it as a bound
the line:why it is allowed: By line 14, with the fixed multiple a half.
guess it, thenthe move: ceiling and floor together
the line:why it is allowed: Lines 11 and 14 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: the dearest change made smaller
the line:numbers average a change 4 2 1 2 10 3 1.9 3.32 1,000 9 7.99 9.97 1,000,000 19 17.95 19.93 A thousand times the numbers adds about 10 to each column. why it is allowed: By lines 4 and 7 of the question on the dearest job, a change made smaller costs at most the climb from the last place, the height . The last place's number made the smallest climbs all of them, by line 2 there. For 4, 2.
the move: a ceiling
the line:why it is allowed: By line 1, as rounding down never makes a number bigger.
guess it, thenthe move: a floor
the line:why it is allowed: By line 1, as rounding down keeps at least half, by line 14 of the question on the dearest job.
guess it, thenthe move: ceiling and floor together
the line:why it is allowed: Lines 2 and 3 bound by the same growth.
guess it, then
try it with a small : at , line 1 gives , which you can work out by hand
the move: a number made bigger sinks
the line:why it is allowed: It got no smaller, so the number above it is still no bigger; only a number below can be smaller. The counted job makes no such change.
the move: price a round
the line:step 22 of 31
8 stands in place 1. The heap keeps a note of where each number stands, so this is one look and no comparison.
comparisons: 0
step 26 of 31
Swap them: 90 sinks below 19.
comparisons: 2
step 29 of 31
Swap them: 90 sinks below 26.
comparisons: 4
step 30 of 31
Nothing is below 90, so it stays.
comparisons: 4
The watch page's second example. 8 at the top becomes 90, sinks below 19, then 26, and stops at place 6. 4 comparisons, 2 swaps. round compares then 1 33 with 90, 19 with 33 swap 90 with 19 2 26 with 90, 52 with 26 swap 90 with 26 no round no child below 90 it stays Each round of that change. Two rounds of 2, then none. why it is allowed: The number itself is the smaller so far at first. So a round makes at most 2 comparisons.
guess it, thenthe move: count the rounds
the line:why it is allowed: is a ceiling. A round needs a child below, so a sink has at most the last place's levels, by line 4 of the question on the dearest job. Each costs at most 2, by line 2. For 7, 2 × 2 is 4, which the second example reaches.
guess it, thenthe move: drop the rounding
the line:why it is allowed: By line 3, as rounding down never makes a number bigger.
guess it, thenthe move: read it as a bound
the line:why it is allowed: By line 4, with the fixed multiple 2.
guess it, then
try it with a small : at , line 3 gives , which you can work out by hand
the move: every place as likely
the line:first change second change comparisons the top the top 1 the top place 2 2 place 2 the top 2 place 2 place 2 3 average 2 Put 3 and 4, then two changes, each picking the top or place 2, so 4 picks, each as likely. why it is allowed: Each number held is as likely, and each has a place of its own, so each place is as likely, whatever the changes before did.
the move: add up the places
the line:place levels to the top 1 0 2 1 3 1 4 2 in all 4 A heap of 4. A change averages 4 times a quarter, which is 1, and four changes give 4. why it is allowed: is the average comparisons, and the climb from place . The puts make . By line 1, a change averages each climb times . Averages add, by line 2 of question 2 of the page expected cost, so changes give times that.
guess it, thenthe move: cancel
the line:why it is allowed: By line 2, as times is 1. For 4, 3 + 0 + 1 + 1 + 2 is 7, the average over all 256 picks.
guess it, thenthe move: name the levels
the line:why it is allowed: By line 2 of the question on the dearest job, is place 's levels, by line 7 of that question.
guess it, thenthe move: the changes alone
the line:why it is allowed: By line 4, taking away the puts' . For 4, 4.
guess it, thenthe move: count the swaps
the line:why it is allowed: By line 5, the changes compare that many times. Each comparison of a change made the smallest swaps, by line 2 of the question on the dearest job, and no put does. For 4, 4.
guess it, thenthe move: count level by level
the line:1 down or more, 6 places
2 down or more, 4 places
A heap of 7, each place showing its levels, 10 in all. place 1 down or more 2 down or more levels 1 0 0 0 2 1 0 1 3 1 0 1 4 1 1 2 5 1 1 2 6 1 1 2 7 1 1 2 in all 6 4 10 Each row adds to its place's levels, and the columns give the brackets, 6 and 4. why it is allowed: By line 4, counting each place once for each level it lies below the top. Level starts at place 2 to the power . Lines 5 and 7 of the box on halving, inside the box under line 4 of the question on the dearest job, show it with for . So the places at least down run from there to .
guess it, thenthe move: gather
the line:why it is allowed: Each of the brackets holds , less a power of 2. For 4, is 2, and 3 + 2 × 5, less 2 + 4, is 7.
guess it, thenthe move: add 1 and take it away
the line:why it is allowed: This changes nothing, and the bracket now starts at 1. For 4, 2 + 4 is 1 + 2 + 4, less 1.
guess it, thenthe move: use the doubling sum, h for n
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 shows a doubling sum from 1 is one less than its next term. For 4, 1 + 2 + 4 is 7, one less than 8.
guess it, thenthe move: take away its 1
the line:why it is allowed: One less, then 1 less again, is two less. For 4, 2 + 4 is 6.
guess it, thenthe move: tidy
the line:why it is allowed: Taking away 2 less than a number takes the number and gives 2 back. For 4, 3 + 10 + 2 less 8 is 7.
guess it, thenthe move: a ceiling from the dearest job
the line:why it is allowed: No pick costs more than the dearest job, by line 8 of the question on it, and line 11 there caps that. So neither does the average.
guess it, thenthe move: read it as a bound
the line:why it is allowed: By line 13, with the fixed multiple 2.
guess it, thenthe move: the last level starts in the row
the line:why it is allowed: Now a floor, above a fixed part of . By line 12. is at most , by line 5 of the box on halving inside the box under line 4 of the question on the dearest job. So is at most , and taking away takes at least as much. At 6, is 13 and the right side 9.
guess it, thenthe move: gather
the line:why it is allowed: , less , plus 2, leaves 1 minus . At 6, 7 × 2, less 6, plus 1, is 9.
guess it, thenthe move: drop what is left over
the line:why it is allowed: Line 16 is plus , which is more than 0. At 6, 6 × 1 + 3 is 9.
guess it, thenthe move: a quarter of h + 1
the line:why it is allowed: From 4 on, is at least 2, and a quarter of is at most . With at 2, three quarters against 1; each 1 more on adds a quarter to the first and 1 to the second.
guess it, thenthe move: a simpler floor
the line:why it is allowed: is less than . At 4, lines 19, 18 and 17 give 2, 3 and 4, and is 7.
guess it, thenthe move: read it as a bound
the line:why it is allowed: By line 19, with the fixed multiple a quarter.
guess it, thenthe move: ceiling and floor together
the line:why it is allowed: Lines 13 and 19 bound by the same growth, , with the fixed multiples 2 and a quarter.
guess it, then
try it on small inputs: over every pick of 4 changes, 256 in all, the average is
the move: look along the row
the line:look for place looks 5 1 1 6 2 2 7 3 3 8 4 4 each once 10 Finding each number of the heap 5, 6, 7, 8 with no note, 10 looks, 2.5 each on average. why it is allowed: A look checks the number at one place against the number wanted.
the move: n changes at random
the line:why it is allowed: is the average looks of changes, each picking a number at random. Each place is as likely, by line 1 of the question on the average, and averages add, as in its line 2.
guess it, thenthe move: use the page on what a structure promises
the line:where does this come from?
question 3 of the page what a structure promisesA dictionary kept as an unsorted row of keys. Look up a key that is there, equally likely to be at any place. How many looks, on average? the move: one look up
the line:look up place looks 17 1 1 42 2 2 8 3 3 22 4 4 all four 10 35, not there 4 Looking up each key of the row 17, 42, 8, 22, kept in the order they came. The four cost 10 looks, 2.5 each on average. why it is allowed: A look compares the key you want with one key of the row, from the front, and the walk stops at the key. Here is the place of the key you want, so places 1 to cost looks. A key that is not there costs a look at every key: looks.
the move: each place times its chance
the line:why it is allowed: Let be the average. means add up: the term after it, once for each from the 1 under it to the over it. With 4 keys each place has chance 1 over 4. So adds 1, 2, 3 and 4 looks, each times 1 over 4: 10 over 4, which is 2.5, the table's average. With keys each chance is 1 over , and by line 1 the key at place costs looks.
the move: use the page on expected cost
the line:where does this come from?
question 1 of the page expected costPick a whole number from 1 to , each as likely. What is its expected value? the move: each value times its chance
the line:times its chance 1 1 over 5 2 2 over 5 3 3 over 5 4 4 over 5 5 5 over 5 in all 15 over 5, which is 3 For 5, each number times its chance, 1 over 5. why it is allowed: The expected value adds each number times its chance, 1 over . , read the sum of, adds the term after it for each from the value under it to the value over it.
the move: take the chance out in front
the line:why it is allowed: Each term is multiplied by 1 over , so multiply once, after adding. For 5, 1 over 5 times 15.
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 whole numbers from 1 to add up to times one more than , halved, as the page on adding up 1 to works out. For 5, 5 times 6, halved, is 15.
the move: cancel the n
the line:why it is allowed: on top and underneath cancel, as is not zero. For 5, 6 over 2 is 3.
the move: read it
the line:why it is allowed: By line 4, halfway between the smallest number, 1, and the biggest, : 3 for 5.
why it is allowed: That page works out this same sum, for a number picked from 1 to , as over 2.
the move: read it
the line:why it is allowed: 1,000 keys cost 500.5 looks on average.
why it is allowed: The box under this line works out the bracket, one look up in a row of , as over 2. For 4, 4 × 2.5 is 10.
guess it, thenthe move: tidy
the line:why it is allowed: For 1,000 numbers, 500,500 looks.
guess it, thenthe move: a ceiling
the line:why it is allowed: By line 4, as is at most .
guess it, thenthe move: a floor
the line:why it is allowed: By line 4, as is more than .
guess it, thenthe move: ceiling and floor together
the line:why it is allowed: Lines 5 and 6 bound by the same growth, , with the fixed multiples 1 and a half.
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 of the dearest job of 4. Put 5, 6, 7 and 8, then make the number at place 4 the smallest, four times; 8->4 means change 8 to 4.
| step | the row | what happens | comparisons | swaps |
|---|---|---|---|---|
| 1 | Start with an empty heap, and 8 operations to do. | 0 | 0 | |
| 2 | 5 | Put 5 at the end of the row, in place 1.5 | 0 | 0 |
| 3 | 5 | 5 is at the top, so it stays.5 | 0 | 0 |
| 4 | 5, 6 | Put 6 at the end of the row, in place 2.5, 6 | 0 | 0 |
| 5 | 5, 6 | 6 is not smaller than 5, the number above it, so it stays.5, 6 | 1 | 0 |
| 6 | 5, 6, 7 | Put 7 at the end of the row, in place 3.5, 6, 7 | 1 | 0 |
| 7 | 5, 6, 7 | 7 is not smaller than 5, the number above it, so it stays.5, 6, 7 | 2 | 0 |
| 8 | 5, 6, 7, 8 | Put 8 at the end of the row, in place 4.5, 6, 7, 8 | 2 | 0 |
| 9 | 5, 6, 7, 8 | 8 is not smaller than 6, the number above it, so it stays.5, 6, 7, 8 | 3 | 0 |
| 10 | 5, 6, 7, 8 | 8 stands in place 4. The heap keeps a note of where each number stands, so this is one look and no comparison.5, 6, 7, 8 | 3 | 0 |
| 11 | 5, 6, 7, 4 | Change 8 to 4. It got smaller, so it is still no bigger than anything below it, but it may need to climb.5, 6, 7, 4 | 3 | 0 |
| 12 | 5, 6, 7, 4 | 4 is smaller than 6, the number above it.5, 6, 7, 4 | 4 | 0 |
| 13 | 5, 4, 7, 6 | Swap them: 4 climbs above 6.5, 4, 7, 6 | 4 | 1 |
| 14 | 5, 4, 7, 6 | 4 is smaller than 5, the number above it.5, 4, 7, 6 | 5 | 1 |
| 15 | 4, 5, 7, 6 | Swap them: 4 climbs above 5.4, 5, 7, 6 | 5 | 2 |
| 16 | 4, 5, 7, 6 | 4 is at the top, so it stays.4, 5, 7, 6 | 5 | 2 |
| 17 | 4, 5, 7, 6 | 6 stands in place 4. The heap keeps a note of where each number stands, so this is one look and no comparison.4, 5, 7, 6 | 5 | 2 |
| 18 | 4, 5, 7, 3 | Change 6 to 3. It got smaller, so it is still no bigger than anything below it, but it may need to climb.4, 5, 7, 3 | 5 | 2 |
| 19 | 4, 5, 7, 3 | 3 is smaller than 5, the number above it.4, 5, 7, 3 | 6 | 2 |
| 20 | 4, 3, 7, 5 | Swap them: 3 climbs above 5.4, 3, 7, 5 | 6 | 3 |
| 21 | 4, 3, 7, 5 | 3 is smaller than 4, the number above it.4, 3, 7, 5 | 7 | 3 |
| 22 | 3, 4, 7, 5 | Swap them: 3 climbs above 4.3, 4, 7, 5 | 7 | 4 |
| 23 | 3, 4, 7, 5 | 3 is at the top, so it stays.3, 4, 7, 5 | 7 | 4 |
| 24 | 3, 4, 7, 5 | 5 stands in place 4. The heap keeps a note of where each number stands, so this is one look and no comparison.3, 4, 7, 5 | 7 | 4 |
| 25 | 3, 4, 7, 2 | Change 5 to 2. It got smaller, so it is still no bigger than anything below it, but it may need to climb.3, 4, 7, 2 | 7 | 4 |
| 26 | 3, 4, 7, 2 | 2 is smaller than 4, the number above it.3, 4, 7, 2 | 8 | 4 |
| 27 | 3, 2, 7, 4 | Swap them: 2 climbs above 4.3, 2, 7, 4 | 8 | 5 |
| 28 | 3, 2, 7, 4 | 2 is smaller than 3, the number above it.3, 2, 7, 4 | 9 | 5 |
| 29 | 2, 3, 7, 4 | Swap them: 2 climbs above 3.2, 3, 7, 4 | 9 | 6 |
| 30 | 2, 3, 7, 4 | 2 is at the top, so it stays.2, 3, 7, 4 | 9 | 6 |
| 31 | 2, 3, 7, 4 | 4 stands in place 4. The heap keeps a note of where each number stands, so this is one look and no comparison.2, 3, 7, 4 | 9 | 6 |
| 32 | 2, 3, 7, 1 | Change 4 to 1. It got smaller, so it is still no bigger than anything below it, but it may need to climb.2, 3, 7, 1 | 9 | 6 |
| 33 | 2, 3, 7, 1 | 1 is smaller than 3, the number above it.2, 3, 7, 1 | 10 | 6 |
| 34 | 2, 1, 7, 3 | Swap them: 1 climbs above 3.2, 1, 7, 3 | 10 | 7 |
| 35 | 2, 1, 7, 3 | 1 is smaller than 2, the number above it.2, 1, 7, 3 | 11 | 7 |
| 36 | 1, 2, 7, 3 | Swap them: 1 climbs above 2.1, 2, 7, 3 | 11 | 8 |
| 37 | 1, 2, 7, 3 | 1 is at the top, so it stays.1, 2, 7, 3 | 11 | 8 |
| 38 | 1, 2, 7, 3 | Done. The heap holds 4 numbers.1, 2, 7, 3 | 11 | 8 |
In all, 11 comparisons. The formula from section 4, , gives at : the same.
where you meet it
Searches over maps change numbers in their heaps all the time.
a shortest route search, Dijkstra's
It finds the shortest way from one town to another, taking the nearest town not yet done each time. A road from that town can shorten another's distance; with a note, that is a change made smaller, as the first table shows.
source: this site's Dijkstra watch page and its module, src/algorithms/networks/dijkstra.ts (pseudocode lines 2 and 4); the books' volume two, chapter 23, its table of uses
cheapest links, Prim's
It joins every town into one network, each time adding the town with the cheapest road to it. Joining a town can make another's road cheaper: again a change made smaller.
source: this site's Prim watch page and its module, src/algorithms/networks/prim.ts (pseudocode lines 2 and 4); the books' volume two, chapter 23, its table of uses
Python's asyncio timers
A timer is a job set for a time. Python's asyncio, its tool for running many tasks at once, keeps timers in a heap with no note. A cancelled timer is marked and thrown away when it reaches the top. Past 100 timers, it rebuilds the heap once over half are cancelled: with 150 timers, once 76 are.
source: CPython's Lib/asyncio/base_events.py (_run_once, and the two limits above it), Python 3.14.4, read offline
| town | distance before | after taking C |
|---|---|---|
| C | 5 | taken, the nearest |
| B | 10 | 9, by 5 + 4, made smaller |
| D | none | 12, by 5 + 7, put in |
| step | the heap's row | cost |
|---|---|---|
| put 3, 9 and 5 | 3, 9, 5 | 2 comparisons |
| look for 9, at places 1 and 2 | 3, 9, 5 | 2 looks |
| move 5, the last, into place 2 | 3, 5 | 1 comparison, 5 stays |
| put 4 | 3, 5, 4 | 1 comparison, 4 stays |
| operation | the heap's row | dead |
|---|---|---|
| put 3, 9 and 5 | 3, 9, 5 | |
| 9 to 4: put 4, mark 9 dead | 3, 4, 5, 9 | 9 |
| take, giving 3 | 4, 9, 5 | 9 |
| take, giving 4 | 5, 9 | 9 |
| take, giving 5 | 9 | 9 |
| take: 9 is dead, thrown away | nothing |
what is used instead
With no note, there are two ways. Remove and put back, the second table: look along the row, move the last number into the found place to climb or sink, then put the new number in. Lazy deletion, the third table, puts the new number in and marks the old one dead.
how it compares
Four ways to keep numbers that change. Only a heap with a note finds a number without looking. A look compares the wanted number with one place; a climb, sink or walking step compares two numbers held. Each counts as a comparison.
| way | find the number | then | changes, each making a number picked at random the smallest |
|---|---|---|---|
| a heap with a note | one read of the note, no comparison | climb up to levels, or sink up to comparisons | , with the puts |
| a heap with no note | a look at each place from 1, on average | the same | looks more, |
| an unsorted row | the same looks | nothing to repair | the same looks; a take then checks all numbers for the smallest |
| a row kept in order | halving, as binary search does: it looks at the middle of what is left | walk to its new place, past every number between | from place , minus 1 steps. Each place as likely, half of on average, as less 1, by the box under line 3 of the question with no note. changes, times that, at most half of ; from 2 on at least a quarter, as is at least half of . So : 6 at 4, 499,500 at 1,000 |
- a heap with a note, the average
- a heap with no note, the average and looks