Building a heap
how it works
The idea in a few sentences and three pictures, then one row made a heap step by step.
A heap keeps numbers in a row, read as a tree: the number in place has its children in places and . No number sits under a bigger one, so the biggest is on top, at the root. To make a whole row a heap, find the last parent, place . Then build from the bottom up: sift each parent down, from the last back to the first. While a child is bigger, swap the number with its bigger child. Both parts below a parent are heaps by then, so its own part becomes one. The row 46, 85, 11, 67, 23, 54, 38 sifts places 3, 2 and 1.
| sift at place | comparisons | swaps |
|---|---|---|
| 3 | 2 | 1 |
| 2 | 2 | 0 |
| 1 | 4 | 2 |
| in all | 8 | 3 |
step 2 of 20
Place 3 is the last with a child. The 4 numbers after it have none, so each is a heap of one already.
what it remembers to know where it is
- parent at place
- not yet
- number sifting down
- not yet
- now at place
- not yet
Where it says not yet, nothing is held there at that moment.
step 6 of 20
Swap 11 down with its bigger child, 54.
what it remembers to know where it is
- parent at place
- 3
- number sifting down
- 11
- now at place
- 3
step 11 of 20
85 is at least as big as both its children, so it stops here.
what it remembers to know where it is
- parent at place
- 2
- number sifting down
- 85
- now at place
- 2
step 15 of 20
Swap 46 down with its bigger child, 85.
what it remembers to know where it is
- parent at place
- 1
- number sifting down
- 46
- now at place
- 1
step 18 of 20
Swap 46 down with its bigger child, 67.
what it remembers to know where it is
- parent at place
- 1
- number sifting down
- 46
- now at place
- 2
step 19 of 20
46 has no children, so it stops here.
what it remembers to know where it is
- parent at place
- 1
- number sifting down
- 46
- now at place
- 4
the steps, in plain words
choose a step to mark the Python, a programming language, that does it
- read the row as a tree: a number's children sit at twice its place and one morePython lines 12 and 16
- the last parent sits at half the row's length, rounded down; the numbers after it have no childrenPython lines 8 and 9
- for each parent, from the last back to the first, sift it downPython lines 9 and 10
- while a child is bigger, swap the number with its bigger childPython lines 11, 13, 14, 15, 16, 17, 18, 19, 20, 21 and 22
- every number is now at least as big as its children: the row is a heapPython line 23
the same in Python
The steps in plain words are what to learn. Python is a programming language, and the code below does the same steps, for those who code. Python numbers the places in a list from 0, not 1: the first number is numbers[0], the second numbers[1], and so on.
def build_heap(row):
"""Make a list of numbers a heap, biggest on top, in the list itself.
Read the list as a tree: Python counts places from 0, so the children
of place p are 2p + 1 and 2p + 2. Sift each parent down, from the last
back to the first. Returns the list.
"""
size = len(row)
for parent in range(size // 2 - 1, -1, -1): # each parent, the last first
place = parent # sift its number down from here
while True:
first = 2 * place + 1 # its first child; the second is next
if first >= size: # no children: it stops
break
big = place # the biggest so far: the number itself
for child in (first, first + 1): # each child in the list
if child < size and row[child] > row[big]:
big = child
if big == place: # no child is bigger: it stops
break
row[place], row[big] = row[big], row[place] # swap it down
place = big # one level down
return row # every number is now at least as big as its children
how it scales
How the comparisons grow, from ten numbers to a million.
Each step across or up is ten times the one before, a log-log plot. A row that is a heap already costs . Its line climbs one step up for each step across: ten times the numbers, ten times the comparisons. Shuffled rows cost about 13 times as many comparisons from 10 to 100 numbers, and 11 times from 100 to 1,000. From there each step costs 10 times as many, about 1.9 comparisons a number.
comparisons, ten times more at each mark up
, how many numbers are in the row, ten times more at each mark to the right
- different numbers shuffled; 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
- a heap already, 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 | 999 | about 999 nanoseconds |
| 100,000 | 99,999 | about 100 microseconds |
| 10,000,000 | 9,999,999 | about 10 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 building a heap makes, as the plot on this page does.
Run it with Python 3.12 or later. For each size n it prints the comparisons
on a row that is a heap already, the cheapest row, and the average over 20
shuffles. The counts are the same on any computer; only the time differs.
"""
import random
class Counted:
"""A number that counts every comparison made with it."""
comparisons = 0
def __init__(self, value):
self.value = value
def __gt__(self, other):
Counted.comparisons += 1
return self.value > other.value
def build_heap(row):
"""Make a list of numbers a heap, biggest on top, in the list itself.
Read the list as a tree: Python counts places from 0, so the children
of place p are 2p + 1 and 2p + 2. Sift each parent down, from the last
back to the first. Returns the list.
"""
size = len(row)
for parent in range(size // 2 - 1, -1, -1): # each parent, the last first
place = parent # sift its number down from here
while True:
first = 2 * place + 1 # its first child; the second is next
if first >= size: # no children: it stops
break
big = place # the biggest so far: the number itself
for child in (first, first + 1): # each child in the list
if child < size and row[child] > row[big]:
big = child
if big == place: # no child is bigger: it stops
break
row[place], row[big] = row[big], row[place] # swap it down
place = big # one level down
return row # every number is now at least as big as its children
def cheapest(n):
"""n, n - 1, down to 1: biggest first, a heap already."""
return list(range(n, 0, -1))
def count(row):
"""How many comparisons building a heap makes on this row."""
Counted.comparisons = 0
build_heap([Counted(x) for x in row])
return Counted.comparisons
if __name__ == "__main__":
random.seed(1)
print(f"{'n':>6} {'a heap already':>15} {'shuffled':>10}")
for n in [10, 100, 1000, 10000]:
shuffles = []
for _ in range(20):
row = list(range(1, n + 1))
random.shuffle(row)
shuffles.append(count(row))
print(f"{n:>6} {count(cheapest(n)):>15} {sum(shuffles) / 20:>10.1f}")
best, worst and average
A row that is a heap already is the cheapest: each parent meets its children once, and nothing moves. Shuffled rows cost more. Their average is measured, and section 4 shows it grows like . There is no worst column. Trying every order shows smallest first, 1, 2, 3 and on, costs the most at 4, 5 and 7 numbers, but not at 6 or 8. So section 4 caps every row 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.
| besta heap already, the cheapest | averagedifferent numbers shuffled; the average over every order, each as likely | |
|---|---|---|
| comparisons | , a heap already | between and ; at 7, between 6 and 12 |
| 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.
| level | places | height | heights in all | depth | depths in all |
|---|---|---|---|---|---|
| 0 | 1 | 3 | 3 | 0 | 0 |
| 1 | 2 | 2 | 4 | 1 | 2 |
| 2 | 4 | 1 | 4 | 2 | 8 |
| 3 | 8 | 0 | 0 | 3 | 24 |
| in all | 15 | 11 | 34 |
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: a sift's first round
the line:A heap already, 92, 74, 81, 33, 60, 18, 47. Each marked parent is at least as big as its children. sift at place its children comparisons 3 18 and 47 2 2 33 and 60 2 1 74 and 81 2 in all 6 Each parent meets its two children, then stops. At place 1, 74 against 92 leaves 92 the bigger so far, and so does 81 against 92; 2 comparisons. 6 in all, no swap. why it is allowed: Each child is compared once with the bigger so far. In a heap already no child is bigger, so every sift stops after that round, and nothing moves.
the move: add up the first rounds
the line:why it is allowed: is the comparisons on a heap already. Place has a child when place is in the row, so when is at most half of . is whole, so the parents are places 1 to . At 7, 2 × 3 = 6 is in the row and 2 × 4 = 8 is not, so places 1 to 3, as section 1's picture marks. A parent has two children when is in the row too, else one.
guess it, thenthe move: every place but the top is a child
the line:where does this come from?
question 2 of the page trees and their wordsFrom place of a tree kept in a row, which places lie one step down, and which one step up? the move: find where a level starts
the line:The tree of 10 places. Its levels start at places 1, 2, 4 and 8, each block in the row starting where the one before ends. why it is allowed: Say place is on level . No level starts until the one above it is used up, so the levels above level are full. For level 3, levels 0 to 2 hold 1, 2 and 4, which is 7 places, so level 3 starts at place 8. In general the levels above form a full tree whose height is one less than . By question 1 of the page trees and their words it holds one place fewer than , so level starts at place . Level 0 is the root alone, at place 1, and 2 to the power 0 is 1.
the move: count what comes before the first child
the line:Places 2 and 3 take their children in turn, 4 and 5, then 6 and 7. So the first child of place 3 comes after the two of place 2. why it is allowed: Let be the place of the first child of . On level , places come before . The row fills level from its left end, each place's children in turn, so each place before has its two children there before 's first. That level starts at place . For place 3, one place comes before it on level 1, so its first child is 4 + 2, place 6.
the move: multiply out
the line:why it is allowed: Twice is twice less twice .
the move: tidy the power
the line:why it is allowed: Twice is .
the move: cancel
the line:why it is allowed: The first and last terms cancel. For place 3, twice 3 is 6, as line 2 found.
the move: the second child is next
the line:why it is allowed: The two children stand side by side. For place 3, places 6 and 7. A place whose first child would fall past the end of the row is a leaf.
the move: halve a first child
the line:why it is allowed: The floor brackets round down, as on the page on halving. Half of is exactly, so rounding changes nothing.
the move: halve a second child
the line:why it is allowed: Half of is and a half, which rounds down to .
the move: read it
the line:why it is allowed: Every place but the root is the first or the second child of some place, twice it or one more, by lines 5 and 6. Halving it and rounding down gives that place back, by lines 7 and 8. For places 6 and 7, place 3.
why it is allowed: The box under this line shows each place but the top has exactly one place above it. So places 2 to are each counted once. For 7, 2 + 2 + 2 is 6; for 6, place 3 has one child, so 2 + 2 + 1 is 5.
guess it, thenthe move: no row costs fewer
the line:why it is allowed: On any row, each sift starts by meeting its place's children, so no row costs less than . A row of 7, 7, 7, 7, 7, 7, 7 costs exactly 6, as no child is bigger.
guess it, thenthe move: which rows cost that
the line:why it is allowed: With no swap, every sift stopped at once, so each parent was at least as big as its children. A swap into a place with no children adds no comparison, so some rows with swaps cost too. In the row 88, 26, 71, 45, 19, 64, 53, the 26 swaps into place 4, which has no children, and the row costs 6.
guess it, thenthe move: a ceiling
the line:why it is allowed: By line 3, 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: Half of is at most from 2 on. At 7, 3.5 is under 6.
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 2 gives , which you can work out by hand
the move: price a round
the line:step 12 of 20
Each part below place 1 is a heap already. Sift its number, 46, down: while a child is bigger, swap it with its bigger child.
comparisons: 0
step 15 of 20
Swap 46 down with its bigger child, 85.
comparisons: 2
step 18 of 20
Swap 46 down with its bigger child, 67.
comparisons: 4
step 19 of 20
46 has no children, so it stops here.
comparisons: 4
The sift at place 1 of section 1's row, its comparisons counted from this sift's start. 46 meets two children and swaps below 85, then below 67, and stops at place 4, which has none. 4 comparisons. why it is allowed: Each child is compared with the bigger so far, the number itself first. So a round makes at most 2 comparisons. The drawing follows 46 in section 1's row.
the move: count the rounds
the line:The number in each place is its height in a row of 10. Place 3's part is places 3, 6 and 7, one level deep, so its height is 1. In all 8. why it is allowed: , the height of place , is the steps from down to the deepest place in its own part. A round needs a child below, so a sift makes at most that many rounds.
guess it, thenthe move: add up every sift
the line:numbers costs the most smallest first 4 4 4 6 5 6 6 6 6 7 6 8 7 8 8 8 8 11 10 14 Every order of 1 to n tried, in comparisons. No order passes , and the cheapest is always . why it is allowed: is a count no row goes past, by lines 1 and 2, as each sift makes at most 2 comparisons in each of its rounds. For 10, 2 × 8 is 16. On a full heap, like 7 or 15, smallest first makes exactly . Every parent there has two children, and each sifting number is smaller than all below it. The sifts before it only move later places. So it sinks to the bottom: rounds of 2. At 7, 2 + 2 + 4 = 8.
guess it, thenthe move: a step down at least doubles
the line:steps down from place 3 places reached in a row of 10 1 6 and 7 yes 2 12 to 15 no One step down from place 3 reaches places 6 and 7, two steps places 12 to 15, past the end. So place 3 is 1 high. why it is allowed: Place 's children are and , as the box at line 3 of the question on a heap already shows. So the places steps under start at place .
guess it, thenthe move: count the places
the line:why it is allowed: Place is in the row when is at most over . A place is a whole number, so at most that rounded down. For 10, at height 2, 10 over 4 is 2.5, so places 1 and 2.
guess it, thenthe move: add the heights level by level
the line:place at least 1 high at least 2 high at least 3 high height 1 1 1 1 3 2 1 1 2 3 1 1 4 1 1 5 1 1 in all 5 2 1 8 A row of 10, places 6 to 10 left out, being 0 high. The columns add to 5, 2 and 1, and the heights to 8. why it is allowed: Count each place once at every height up to its own, by line 5. is the top's height, and no place is higher. For 10, 5 + 2 + 1 is 8.
guess it, thenthe move: drop the rounding
the line:why it is allowed: Rounding down never makes a number bigger; 2.5 becomes 2. For 10, 5 + 2.5 + 1.25 is 8.75.
guess it, thenthe move: take n out
the line:why it is allowed: Each term is times a halving term.
guess it, thenthe move: use the halving sum
the line:where does this come from?
question 2 of the page doubling and halving sumsAdd . How close does it come to 1? the move: name the sum
the line:Line 1 for 3, 7 over 8, short of 1 by 1 over 8. why it is allowed: Let be the halving sum from one half down to 1 over . The bars add it for 3.
the move: double both sides
the line:why it is allowed: As in question 1 of the page doubling and halving sums: double, take away, and all but the ends cancel. Doubled, one half becomes 1, and 1 over becomes 1 over , as is twice . For 3, 2 × 1 over 8 is 2 over 8, which is 1 over 4.
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:why it is allowed: Every term from one half to 1 over is in both brackets and cancels, leaving 1 less 1 over . For 3, 1 less 1 over 8 is 7 over 8.
the move: a ceiling
the line:why it is allowed: Line 5 takes 1 over , above zero, from 1, so is under 1, and so at most 1.
the move: read it
the line:why it is allowed: By line 5 the sum falls short of 1 by its last term, which halves each time but never reaches zero. Line 6 makes 1 its ceiling.
why it is allowed: The box under this line adds the halving sum, its being here. It falls short of 1 by its last term. For 10, is 3, and 1 less 1 over 8 is 7 over 8.
guess it, thenthe move: multiply out
the line:why it is allowed: Twice times each part. For 10, 20 less 2.5 is 17.5.
guess it, thenthe move: the top's path ends in the row
the line:The top's path down by first children, places 1, 2, 4 and 8, ends inside a row of 10. The small number beside each place counts its steps up from place 8, so the top is 3 high. 2 × 10 over 8 is 2.5, so is at most 17.5, under 18. why it is allowed: The top is high, so by line 4 place is in the row. So is at most , and is at least 2. Taking away at least 2 leaves at most .
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: every row grows in step with n
the line:why it is allowed: No row goes past , so none past , by line 11, and none costs less than , by the question on a heap already. Both grow in step with . Each round makes at most 2 comparisons and at most 1 swap, so the swaps are at most half of , at most by line 11. For 10, at most 8 swaps, fewer than the 10 numbers.
guess it, then
try it with a small : at , line 3 gives , which you can work out by hand
the move: a put climbs
the line:A put making 8 starts at place 8 and climbs through places 4 and 2 to place 1, three levels, the depth of place 8. The small number beside each place counts the levels climbed to reach it. why it is allowed: The -th number put in goes at the end, place , and swaps with the number above it while bigger, one comparison a level, none at the top. Every put after the first starts below the top, so it compares at least once. Biggest first, each compares once and stays, in all, the fewest.
the move: smallest first climbs all the way
the line:put starts at place levels to the top comparisons 14 1 0 0 22 2 1 1 37 3 1 1 41 4 2 2 56 5 2 2 63 6 2 2 78 7 2 2 95 8 3 3 Smallest first, one at a time. Each climbs to the top, one comparison a level, 13 in all. why it is allowed: is the comparisons when the numbers come smallest first. Each is bigger than every number already in, so it climbs all the way to place 1, one comparison a level.
guess it, thenthe move: name the levels
the line:place levels down 1 0 0 2 to 3 1 1 4 to 7 2 2 8 to 15 3 3 Each level's places, and the power of 2 each place reaches, rounded down. The two columns match. 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 the last place of a row of places lies levels down. For 8, 1 + 1 + 2 + 2 + 2 + 2 + 3 is 13, as in line 2's picture.
guess it, thenthe move: no order climbs more
the line:put climbs comparisons 30 0 1 70 1 2 90 2 2 Each put into the heap 80, 60, 50, 20, 40, 10, making 7. 30 stays under 50; 70 passes 50 and stops under 80; 90 climbs to the top. None costs more than 2, the levels from place 7 up. why it is allowed: A climb to the top costs one comparison a level. One that stops early costs one more, to stop, but climbs a level fewer at least. So no order costs more than .
guess it, thenthe move: a ceiling
the line:why it is allowed: Line 3 has terms, each at most .
guess it, thenthe move: round up to
the line:why it is allowed: is less than . At 8, 13 is at most 24.
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: drop the first half
the line:Each place's climb in a heap of 8. The ringed places past half of 8, places 5 to 8, climb 2, 2, 2 and 3. why it is allowed: Keep only the puts past the middle, places to . The others climb 0 or more. At 8, places 5 to 8 climb 2 + 2 + 2 + 3, which is 9.
guess it, thenthe move: each kept put climbs far
the line:why it is allowed: A place past half of has no child, as twice it is past place , one level lower. The levels fill in order, as the box under line 3 of the question on a heap already shows. So place is at most one level below the place, which climbs at least . At 8, twice place 5 is 10, past 8, so place 8 is one level below place 5. At least half the puts are kept, so 4 puts of at least 2 make 8.
guess it, thenthe move: drop the rounding
the line:why it is allowed: Rounding down takes off less than 1. This is the floor section 7's plot draws. At 10, is 3 and about 3.32, so 5 × 2 = 10 becomes 5 × 1.32, about 6.6.
guess it, thenthe move: a simpler floor
the line:numbers half of 8 2 1.5 15 2 1.95 16 3 2 32 4 2.5 The middle column never falls below the last from 8 on. They come closest just below a power of 2, 2 against 1.95 at 15. why it is allowed: By line 9. is below one more than . Half of that one more is at most exactly when is 3 or more, so from 8 on. When it is 3, half of 4 is 2, against 3 - 1 = 2. So times is at least times half of , which is . At 8, 2 is at least 1.5, 4 × 1.5 = 6, and 13 is at least 6.
guess it, thenthe move: read it as a bound
the line:why it is allowed: By line 11, with the fixed multiple a quarter, from 8 on.
guess it, thenthe move: ceiling and floor together
the line:why it is allowed: Lines 6 and 11 bound by the same growth. Bottom up, by the question on the ceiling, never passes .
guess it, then
try it with a small : at , line 2 gives , which you can work out by hand
the move: a floor from every row
the line:numbers average per number 10 13.1 1.31 100 175.8 1.76 1,000 1,869.9 1.87 10,000 18,791.4 1.88 1,000,000 1,881,312.5 1.88 Comparisons on shuffled rows of 1 to n, the mean of 20 shuffles, as the plot's points. From 1,000 on, about 1.9 a number. why it is allowed: is the average comparisons over every order of different numbers. No row costs less than , by the question on a heap already, so neither does the average. At 7, the average over all 5,040 orders, 7 × 6 × 5 × 4 × 3 × 2 × 1, is about 7.71, above 6.
the move: a simpler floor
the line:why it is allowed: Half of is at most from 2 on.
guess it, thenthe move: read it as a bound
the line:why it is allowed: By line 2, with the fixed multiple a half.
guess it, thenthe move: a ceiling from every row
the line:why it is allowed: No row goes past , by the question on the ceiling, so neither does the average.
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, thenthe move: ceiling and floor together
the line:why it is allowed: Lines 2 and 4 bound by the same growth, .
guess it, then
try it on small rows: over every order of 7 numbers, the average is about 7.71
count it yourself
Count every comparison as 77, 52, 69, 18, 40, 63, 25 is made a heap. It is one already, so nothing moves.
| step | the row | what happens | comparisons | swaps |
|---|---|---|---|---|
| 1 | 77, 52, 69, 18, 40, 63, 25 | There are 7 numbers in a row, drawn below as a tree: the number in place p has its children in places 2p and 2p + 1.77, 52, 69, 18, 40, 63, 25 | 0 | 0 |
| 2 | 77, 52, 69, 18, 40, 63, 25 | Place 3 is the last with a child. The 4 numbers after it have none, so each is a heap of one already.77, 52, 69, 18, 40, 63, 25 | 0 | 0 |
| 3 | 77, 52, 69, 18, 40, 63, 25 | Each part below place 3 is a heap already. Sift its number, 69, down: while a child is bigger, swap it with its bigger child.77, 52, 69, 18, 40, 63, 25 | 0 | 0 |
| 4 | 77, 52, 69, 18, 40, 63, 25 | 63 is not bigger than 69.77, 52, 69, 18, 40, 63, 25 | 1 | 0 |
| 5 | 77, 52, 69, 18, 40, 63, 25 | 25 is not bigger than 69.77, 52, 69, 18, 40, 63, 25 | 2 | 0 |
| 6 | 77, 52, 69, 18, 40, 63, 25 | 69 is at least as big as both its children, so it stops here.77, 52, 69, 18, 40, 63, 25 | 2 | 0 |
| 7 | 77, 52, 69, 18, 40, 63, 25 | Each part below place 2 is a heap already. Sift its number, 52, down: while a child is bigger, swap it with its bigger child.77, 52, 69, 18, 40, 63, 25 | 2 | 0 |
| 8 | 77, 52, 69, 18, 40, 63, 25 | 18 is not bigger than 52.77, 52, 69, 18, 40, 63, 25 | 3 | 0 |
| 9 | 77, 52, 69, 18, 40, 63, 25 | 40 is not bigger than 52.77, 52, 69, 18, 40, 63, 25 | 4 | 0 |
| 10 | 77, 52, 69, 18, 40, 63, 25 | 52 is at least as big as both its children, so it stops here.77, 52, 69, 18, 40, 63, 25 | 4 | 0 |
| 11 | 77, 52, 69, 18, 40, 63, 25 | Each part below place 1 is a heap already. Sift its number, 77, down: while a child is bigger, swap it with its bigger child.77, 52, 69, 18, 40, 63, 25 | 4 | 0 |
| 12 | 77, 52, 69, 18, 40, 63, 25 | 52 is not bigger than 77.77, 52, 69, 18, 40, 63, 25 | 5 | 0 |
| 13 | 77, 52, 69, 18, 40, 63, 25 | 69 is not bigger than 77.77, 52, 69, 18, 40, 63, 25 | 6 | 0 |
| 14 | 77, 52, 69, 18, 40, 63, 25 | 77 is at least as big as both its children, so it stops here.77, 52, 69, 18, 40, 63, 25 | 6 | 0 |
| 15 | 77, 52, 69, 18, 40, 63, 25 | Every number is at least as big as its children, so the row is a heap, with the biggest, 77, at the top. It took 6 comparisons and no swaps.77, 52, 69, 18, 40, 63, 25 | 6 | 0 |
In all, 6 comparisons. The formula from section 4, , gives at : the same.
where you meet it
Python builds heaps from whole lists, bottom up.
Python's heapify
Python comes with heapq, ready-made code that keeps a heap in a plain list, smallest on top. Its heapify makes a whole list a heap in the list itself, bottom up from the parents, not one put at a time. Its sift is not this page's, so its counts differ. Its note says it takes time in step with the list's length.
source: CPython's Lib/heapq.py (heapify, its note, and the note above _siftup), Python 3.14.4, read offline
the few biggest of many numbers
Python's heapq.nlargest finds, say, the 3 biggest numbers of a long list. It makes the first 3 a heap, the smallest on top, and keeps a later number only if it beats that top.
source: CPython's Lib/heapq.py (nlargest), Python 3.14.4, read offline; the books' 'In the wild' sidebar, volume two, chapter 24
| number | beats the top? | the 3 kept | top |
|---|---|---|---|
| 5, 9, 2 | the first 3 | 2, 5, 9 | 2 |
| 7 | yes, 7 beats 2 | 5, 7, 9 | 5 |
| 8 | yes, 8 beats 5 | 7, 8, 9 | 7 |
| 1 | no | 7, 8, 9 | 7 |
what is used instead
When the numbers arrive one at a time, while you take from the top, put each in as it comes, as binary heap's learn page does. On shuffled numbers that costs little more: about 2.2 comparisons a number against about 1.9 bottom up, at 1,000 numbers. Sebastian Bourges' books, Algorithmic Thinking Without the Jargon, volume two, chapter 24, put the choice plainly: 'Reach for heapify whenever you have all the items already.'
how it compares
Two ways to make a heap of numbers, side by side. On shuffled numbers one at a time costs a little more, as section 6 measures. Smallest first sets them apart.
| comparisons | one at a time | bottom up |
|---|---|---|
| fewest | , biggest first | , a heap already |
| most | at most , smallest first | at most |
| growth | , smallest first | , every row |
| numbers | one at a time | bottom up |
|---|---|---|
| 15 | 34 (2.27) | 22 (1.47) |
| 31 | 98 (3.16) | 52 (1.68) |
| 63 | 258 (4.10) | 114 (1.81) |
| 1,023 | 8,194 (8.01) | 2,026 (1.98) |
- one at a time at most,
- smallest first, one at a time, at least
- bottom up at most,
- bottom up at least,