Skip to content

Building a heap

storing

Level 2 of 3

Also called Heapify, Floyd's method and Bottom-up heap construction.

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 pp has its children in places 2p2p and 2p+12p + 1. 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 ⌊n/2⌋\lfloor n / 2 \rfloor. 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.

46851167235438461852113674235546387
The row as a tree above the same row. The marked places 1, 2 and 3 are the parents. Places 4 to 7 have no children, so each is a heap of one.
sift at placecomparisonsswaps
321
220
142
in all83
Each sift of that row, in turn. 11 drops below 54; 85 stays; 46 drops twice. 8 comparisons and 3 swaps make it a heap.
46855467231138461852543674235116387
The row as place 1's sift begins. The parts under places 2 and 3 are heaps now, and only 46 is out of place. It sinks below 85, then 67, and the heap ends 85, 67, 54, 46, 23, 11, 38.
A short shuffle: 6 moments of its 20 steps, the steps between them left for the watch page
  1. step 2 of 20

    46851167235438146285311467523654738

    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.

    watch from here

  2. step 6 of 20

    46855467231138146285354467523611738

    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

    watch from here

  3. step 11 of 20

    46855467231138146285354467523611738

    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

    watch from here

  4. step 15 of 20

    85465467231138185246354467523611738

    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

    watch from here

  5. step 18 of 20

    85675446231138185267354446523611738

    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

    watch from here

  6. step 19 of 20

    85675446231138185267354446523611738

    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

    watch from here

the steps, in plain words
  1. read the row as a tree: a number's children sit at twice its place and one morePython lines 12 and 16
  2. the last parent sits at half the row's length, rounded down; the numbers after it have no childrenPython lines 8 and 9
  3. for each parent, from the last back to the first, sift it downPython lines 9 and 10
  4. 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
  5. 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 n−1n - 1. 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

slope 1102104106101102103104105106107slope 1101102103104105106107101102103104105106107slope 1101102103104105106107101102103104105106107

nn, 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
what a cheapest row costs, at a billion comparisons a second
nncomparisonstime
1,000999about 999 nanoseconds
100,00099,999about 100 microseconds
10,000,0009,999,999about 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 nn. 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.

what each case costs, and how fast that cost grows; section 4 works out every formula in it
besta heap already, the cheapestaveragedifferent numbers shuffled; the average over every order, each as likely
comparisonsn−1n - 1, a heap alreadybetween n−1n - 1 and 2n−22n - 2; at 7, between 6 and 12
how the comparisons grow in each case
tight, Θ\ThetaΘ(n)\Theta(n)Θ(n)\Theta(n)
ceiling, OOO(n)O(n)O(n)O(n)
floor, Ω\OmegaΩ(n)\Omega(n)Ω(n)\Omega(n)

extra memory: a few places beside the row that holds the numbers

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

322111100000000312223141516170809010011012013014015
A full heap of 15, every level full. The number in each place is its height, the most a number there can sink. The 8 on the bottom sink none, and only the top can sink 3.
depth01230112222333333330112132425262738393103113123133143150123
The same heap, each place showing its depth, the most a number put there can climb when numbers go in one at a time. The 8 on the bottom can climb 3 each.
levelplacesheightheights in alldepthdepths in all
013300
122412
241428
3800324
in all151134
The two trees level by level. Each level's places times its height, and times its depth. Most places are low, so the heights stay small and the depths do not.

where the formula comes from

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

Why does a row that is a heap already cost exactly n−1n - 1 comparisons, the fewest any row can?
  1. the move: a sift's first round

    the line:
    a sift first compareseach child of its place\begin{gathered} \text{a sift first compares} \\ \text{each child of its place} \end{gathered}
    92748133601847921742813334605186477
    A heap already, 92, 74, 81, 33, 60, 18, 47. Each marked parent is at least as big as its children.
    sift at placeits childrencomparisons
    318 and 472
    233 and 602
    174 and 812
    in all6
    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.

  2. the move: add up the first rounds

    the line:
    B=how many children places1 to ⌊n/2⌋ haveB = \begin{gathered} \text{how many children places} \\ 1 \text{ to } \lfloor n / 2 \rfloor \text{ have} \end{gathered}

    why it is allowed: BB is the comparisons on a heap already. Place pp has a child when place 2p2p is in the row, so when pp is at most half of nn. pp is whole, so the parents are places 1 to ⌊n/2⌋\lfloor n / 2 \rfloor. 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 2p+12p + 1 is in the row too, else one.

  3. the move: every place but the top is a child

    the line:
    B=n−1B = n - 1
    where does this come from?
    question 2 of the page trees and their wordsFrom place ii of a tree kept in a row, which places lie one step down, and which one step up?
    1. the move: find where a level starts

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

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

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

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

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

    3. the move: multiply out

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

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

    4. the move: tidy the power

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

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

    5. the move: cancel

      the line:
      C=2iC = 2i

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

    6. the move: the second child is next

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

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

    7. the move: halve a first child

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

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

    8. the move: halve a second child

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

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

    9. the move: read it

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

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

    the whole page: trees and their words

    why it is allowed: The box under this line shows each place but the top has exactly one place above it. So places 2 to nn are each counted once. For 7, 2 + 2 + 2 is 6; for 6, place 3 has one child, so 2 + 2 + 1 is 5.

  4. the move: no row costs fewer

    the line:
    every row makesthese first rounds\begin{gathered} \text{every row makes} \\ \text{these first rounds} \end{gathered}

    why it is allowed: On any row, each sift starts by meeting its place's children, so no row costs less than n−1n - 1. A row of 7, 7, 7, 7, 7, 7, 7 costs exactly 6, as no child is bigger.

  5. the move: which rows cost that

    the line:
    a row with no swapwas a heap already\begin{gathered} \text{a row with no swap} \\ \text{was a heap already} \end{gathered}

    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 n−1n - 1 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.

  6. the move: a ceiling

    the line:
    B≤nB \le n

    why it is allowed: By line 3, taking 1 away.

  7. the move: read it as a bound

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

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

  8. the move: a floor

    the line:
    B≥n2 for n≥2B \ge \frac{n}{2} \text{ for } n \ge 2

    why it is allowed: Half of nn is at most n−1n - 1 from 2 on. At 7, 3.5 is under 6.

  9. the move: read it as a bound

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

    why it is allowed: By line 8, with the fixed multiple a half.

  10. the move: ceiling and floor together

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

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

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

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

    the line:
    a round at place p comparesits children, 2p and 2p+1,then stops or drops a level\begin{gathered} \text{a round at place } p \text{ compares} \\ \text{its children, } 2p \text{ and } 2p + 1 \text{,} \\ \text{then stops or drops a level} \end{gathered}
    1. step 12 of 20

      46855467231138

      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

    2. step 15 of 20

      85465467231138

      Swap 46 down with its bigger child, 85.

      comparisons: 2

    3. step 18 of 20

      85675446231138

      Swap 46 down with its bigger child, 67.

      comparisons: 4

    4. step 19 of 20

      85675446231138

      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.

  2. the move: count the rounds

    the line:
    a sift from place pmakes at most hp rounds\begin{gathered} \text{a sift from place } p \\ \text{makes at most } h_p \text{ rounds} \end{gathered}
    3211100000312213141506070809010
    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: hph_p, the height of place pp, is the steps from pp down to the deepest place in its own part. A round needs a child below, so a sift makes at most that many rounds.

  3. the move: add up every sift

    the line:
    U=2(h1+h2+⋯+hn)U = 2(h_1 + h_2 + \dots + h_n)
    numberscosts the mostsmallest firstUU
    4446
    5666
    6768
    7888
    8111014
    Every order of 1 to n tried, in comparisons. No order passes UU, and the cheapest is always n−1n - 1.

    why it is allowed: UU 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 UU. 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: hph_p rounds of 2. At 7, 2 + 2 + 4 = 8.

  4. the move: a step down at least doubles

    the line:
    so p is at least k high exactlywhen place 2kp is in the row\begin{gathered} \text{so } p \text{ is at least } k \text{ high exactly} \\ \text{when place } 2^k p \text{ is in the row} \end{gathered}
    steps down from place 3places reachedin a row of 10
    16 and 7yes
    212 to 15no
    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 pp's children are 2p2p and 2p+12p + 1, as the box at line 3 of the question on a heap already shows. So the places kk steps under pp start at place 2kp2^k p.

  5. the move: count the places

    the line:
    so places 1 to ⌊n/2k⌋are at least k high\begin{gathered} \text{so places 1 to } \lfloor n / 2^k \rfloor \\ \text{are at least } k \text{ high} \end{gathered}

    why it is allowed: Place 2kp2^k p is in the row when pp is at most nn over 2k2^k. 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.

  6. the move: add the heights level by level

    the line:
    U=2(⌊n/2⌋+⌊n/4⌋+⋯+⌊n/2K⌋)\begin{aligned} U = 2\bigl(&\lfloor n / 2 \rfloor + \lfloor n / 4 \rfloor \\ &+ \dots + \lfloor n / 2^K \rfloor\bigr) \end{aligned}
    placeat least 1 highat least 2 highat least 3 highheight
    11113
    2112
    311
    411
    511
    in all5218
    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. KK is the top's height, and no place is higher. For 10, 5 + 2 + 1 is 8.

  7. the move: drop the rounding

    the line:
    U≤2(n2+n4+⋯+n2K)U \le 2\Bigl(\frac{n}{2} + \frac{n}{4} + \dots + \frac{n}{2^K}\Bigr)

    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.

  8. the move: take n out

    the line:
    U≤2n(12+14+⋯+12K)U \le 2n\Bigl(\frac{1}{2} + \frac{1}{4} + \dots + \frac{1}{2^K}\Bigr)

    why it is allowed: Each term is nn times a halving term.

  9. the move: use the halving sum

    the line:
    U≤2n(1−12K)U \le 2n\Bigl(1 - \frac{1}{2^K}\Bigr)
    where does this come from?
    question 2 of the page doubling and halving sumsAdd 12+14+⋯+12n\frac{1}{2} + \frac{1}{4} + \dots + \frac{1}{2^n}. How close does it come to 1?
    1. the move: name the sum

      the line:
      H=12+14+⋯+12nH = \frac{1}{2} + \frac{1}{4} + \dots + \frac{1}{2^n}
      Line 1 for 3, 7 over 8, short of 1 by 1 over 8.

      why it is allowed: Let HH be the halving sum from one half down to 1 over 2n2^n. The bars add it for 3.

    2. the move: double both sides

      the line:
      2H=1+12+⋯+12n−12H = 1 + \frac{1}{2} + \dots + \frac{1}{2^{n - 1}}

      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 2n2^n becomes 1 over 2n−12^{n - 1}, as 2n2^n is twice 2n−12^{n - 1}. For 3, 2 × 1 over 8 is 2 over 8, which is 1 over 4.

    3. the move: take line 1 away

      the line:
      2H−H=(1+⋯+12n−1)−(12+⋯+12n)\begin{aligned} 2H - H = {} & \left(1 + \dots + \frac{1}{2^{n - 1}}\right) \\ & - \left(\frac{1}{2} + \dots + \frac{1}{2^n}\right) \end{aligned}

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

    4. the move: tidy the left side

      the line:
      H=(1+⋯+12n−1)−(12+⋯+12n)\begin{aligned} H = {} & \left(1 + \dots + \frac{1}{2^{n - 1}}\right) \\ & - \left(\frac{1}{2} + \dots + \frac{1}{2^n}\right) \end{aligned}

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

    5. the move: cancel what both brackets share

      the line:
      H=1−12nH = 1 - \frac{1}{2^n}

      why it is allowed: Every term from one half to 1 over 2n−12^{n - 1} is in both brackets and cancels, leaving 1 less 1 over 2n2^n. For 3, 1 less 1 over 8 is 7 over 8.

    6. the move: a ceiling

      the line:
      H≤1H \le 1

      why it is allowed: Line 5 takes 1 over 2n2^n, above zero, from 1, so HH is under 1, and so at most 1.

    7. the move: read it

      the line:
      ever closer to 1,never reaching it\begin{gathered} \text{ever closer to 1,} \\ \text{never reaching it} \end{gathered}

      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.

    the whole page: doubling and halving sums

    why it is allowed: The box under this line adds the halving sum, its nn being KK here. It falls short of 1 by its last term. For 10, KK is 3, and 1 less 1 over 8 is 7 over 8.

  10. the move: multiply out

    the line:
    U≤2n−2n2KU \le 2n - \frac{2n}{2^K}

    why it is allowed: Twice nn times each part. For 10, 20 less 2.5 is 17.5.

  11. the move: the top's path ends in the row

    the line:
    U≤2n−2U \le 2n - 2
    13223415678091012345678910
    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 UU is at most 17.5, under 18.

    why it is allowed: The top is KK high, so by line 4 place 2K2^K is in the row. So 2K2^K is at most nn, and 2n2K\frac{2n}{2^K} is at least 2. Taking away at least 2 leaves at most 2n−22n - 2.

  12. the move: read it as a bound

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

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

  13. the move: every row grows in step with n

    the line:
    every row costs from n−1to 2n−2, so Θ(n)\begin{gathered} \text{every row costs from } n - 1 \\ \text{to } 2n - 2 \text{, so } \Theta(n) \end{gathered}

    why it is allowed: No row goes past UU, so none past 2n−22n - 2, by line 11, and none costs less than n−1n - 1, by the question on a heap already. Both grow in step with nn. Each round makes at most 2 comparisons and at most 1 swap, so the swaps are at most half of UU, at most n−1n - 1 by line 11. For 10, at most 8 swaps, fewer than the 10 numbers.

try it with a small nn: at n=10n = 10, line 3 gives U=16U = 16, which you can work out by hand

Put the numbers in one at a time instead, as binary heap's page does. What can that cost?
  1. the move: a put climbs

    the line:
    a put making m starts atplace m and climbs while bigger\begin{gathered} \text{a put making } m \text{ starts at} \\ \text{place } m \text{ and climbs while bigger} \end{gathered}
    13223415678012345678
    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 mm-th number put in goes at the end, place mm, 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, n−1n - 1 in all, the fewest.

  2. the move: smallest first climbs all the way

    the line:
    G=levels from place 2 to the top+⋯+levels from place n\begin{gathered} G = \text{levels from place 2 to the top} \\ + \dots + \text{levels from place } n \end{gathered}
    putstarts at placelevels to the topcomparisons
    14100
    22211
    37311
    41422
    56522
    63622
    78722
    95833
    Smallest first, one at a time. Each climbs to the top, one comparison a level, 13 in all.

    why it is allowed: GG 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.

  3. the move: name the levels

    the line:
    G=⌊log⁡2 2⌋+⋯+⌊log⁡2 n⌋G = \lfloor \log_2\, 2 \rfloor + \dots + \lfloor \log_2\, n \rfloor
    place mmlevels down⌊log⁡2 m⌋\lfloor \log_2\, m \rfloor
    100
    2 to 311
    4 to 722
    8 to 1533
    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 nn places kept in a row. What is its height?
    1. the move: the last place is the deepest

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

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

    2. the move: each step up halves

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

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

    3. the move: count the steps

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

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

    4. the move: use halving and logarithms

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

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

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

      2. the move: rounding down never adds

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

      8. the move: halve both sides of line 5

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

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

      9. the move: write the half as a power

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

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

      10. the move: round the half down

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

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

      11. the move: halve both sides of line 7

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

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

      12. the move: write the half as a power

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

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

      13. the move: round the half down

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

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

      14. the move: take the log of line 10

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

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

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

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

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

      16. the move: take the log of line 13

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

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

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

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

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

      18. the move: round the log down

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

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

      19. the move: use line 18 again and again

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

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

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

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

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

      the whole page: halving and logarithms

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

    5. the move: read it

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

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

    the whole page: trees and their words

    why it is allowed: The box under this line shows the last place of a row of mm places lies ⌊log⁡2 m⌋\lfloor \log_2\, m \rfloor levels down. For 8, 1 + 1 + 2 + 2 + 2 + 2 + 3 is 13, as in line 2's picture.

  4. the move: no order climbs more

    the line:
    a put making m comparesat most ⌊log⁡2 m⌋ times\begin{gathered} \text{a put making } m \text{ compares} \\ \text{at most } \lfloor \log_2\, m \rfloor \text{ times} \end{gathered}
    putclimbscomparisons
    3001
    7012
    9022
    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 GG.

  5. the move: a ceiling

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

    why it is allowed: Line 3 has n−1n - 1 terms, each at most log⁡2 n\log_2\, n.

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

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

    why it is allowed: n−1n - 1 is less than nn. At 8, 13 is at most 24.

  7. the move: read it as a bound

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

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

  8. the move: drop the first half

    the line:
    G≥⌊log⁡2(⌊n/2⌋+1)⌋+⋯+⌊log⁡2 n⌋G \ge \lfloor \log_2 (\lfloor n / 2 \rfloor + 1) \rfloor + \dots + \lfloor \log_2\, n \rfloor
    011222230112132425262738
    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 ⌊n/2⌋+1\lfloor n / 2 \rfloor + 1 to nn. The others climb 0 or more. At 8, places 5 to 8 climb 2 + 2 + 2 + 3, which is 9.

  9. the move: each kept put climbs far

    the line:
    G≥n2(⌊log⁡2 n⌋−1)G \ge \frac{n}{2}(\lfloor \log_2\, n \rfloor - 1)

    why it is allowed: A place past half of nn has no child, as twice it is past place nn, one level lower. The levels fill in order, as the box under line 3 of the question on a heap already shows. So place nn is at most one level below the place, which climbs at least ⌊log⁡2 n⌋−1\lfloor \log_2\, n \rfloor - 1. 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.

  10. the move: drop the rounding

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

    why it is allowed: Rounding down takes off less than 1. This is the floor section 7's plot draws. At 10, ⌊log⁡2 n⌋\lfloor \log_2\, n \rfloor is 3 and log⁡2 n\log_2\, n about 3.32, so 5 × 2 = 10 becomes 5 × 1.32, about 6.6.

  11. the move: a simpler floor

    the line:
    G≥n log⁡2 n4 for n≥8G \ge \frac{n \,\log_2\, n}{4} \text{ for } n \ge 8
    numbers⌊log⁡2 n⌋−1\lfloor \log_2\, n \rfloor - 1half of log⁡2 n\log_2\, n
    821.5
    1521.95
    1632
    3242.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. log⁡2 n\log_2\, n is below one more than ⌊log⁡2 n⌋\lfloor \log_2\, n \rfloor. Half of that one more is at most ⌊log⁡2 n⌋−1\lfloor \log_2\, n \rfloor - 1 exactly when ⌊log⁡2 n⌋\lfloor \log_2\, n \rfloor is 3 or more, so from 8 on. When it is 3, half of 4 is 2, against 3 - 1 = 2. So n2\frac{n}{2} times ⌊log⁡2 n⌋−1\lfloor \log_2\, n \rfloor - 1 is at least n2\frac{n}{2} times half of log⁡2 n\log_2\, n, which is n log⁡2 n4\frac{n \,\log_2\, n}{4}. At 8, 2 is at least 1.5, 4 × 1.5 = 6, and 13 is at least 6.

  12. the move: read it as a bound

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

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

  13. the move: ceiling and floor together

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

    why it is allowed: Lines 6 and 11 bound GG by the same growth. Bottom up, by the question on the ceiling, never passes 2n−22n - 2.

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

Why does a shuffled row cost Θ(n)\Theta(n) comparisons on average?
  1. the move: a floor from every row

    the line:
    A≥n−1A \ge n - 1
    numbersaverageper number
    1013.11.31
    100175.81.76
    1,0001,869.91.87
    10,00018,791.41.88
    1,000,0001,881,312.51.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: AA is the average comparisons over every order of nn different numbers. No row costs less than n−1n - 1, 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.

  2. the move: a simpler floor

    the line:
    A≥n2 for n≥2A \ge \frac{n}{2} \text{ for } n \ge 2

    why it is allowed: Half of nn is at most n−1n - 1 from 2 on.

  3. the move: read it as a bound

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

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

  4. the move: a ceiling from every row

    the line:
    A≤2n−2A \le 2n - 2

    why it is allowed: No row goes past 2n−22n - 2, by the question on the ceiling, so neither does the average.

  5. the move: read it as a bound

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

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

  6. the move: ceiling and floor together

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

    why it is allowed: Lines 2 and 4 bound AA by the same growth, nn.

try it on small rows: over every order of 7 numbers, the average AA 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.

77, 52, 69, 18, 40, 63, 25, every step written down
stepthe rowwhat happenscomparisonsswaps
177, 52, 69, 18, 40, 63, 25There 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, 2500
277, 52, 69, 18, 40, 63, 25Place 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, 2500
377, 52, 69, 18, 40, 63, 25Each 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, 2500
477, 52, 69, 18, 40, 63, 2563 is not bigger than 69.77, 52, 69, 18, 40, 63, 2510
577, 52, 69, 18, 40, 63, 2525 is not bigger than 69.77, 52, 69, 18, 40, 63, 2520
677, 52, 69, 18, 40, 63, 2569 is at least as big as both its children, so it stops here.77, 52, 69, 18, 40, 63, 2520
777, 52, 69, 18, 40, 63, 25Each 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, 2520
877, 52, 69, 18, 40, 63, 2518 is not bigger than 52.77, 52, 69, 18, 40, 63, 2530
977, 52, 69, 18, 40, 63, 2540 is not bigger than 52.77, 52, 69, 18, 40, 63, 2540
1077, 52, 69, 18, 40, 63, 2552 is at least as big as both its children, so it stops here.77, 52, 69, 18, 40, 63, 2540
1177, 52, 69, 18, 40, 63, 25Each 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, 2540
1277, 52, 69, 18, 40, 63, 2552 is not bigger than 77.77, 52, 69, 18, 40, 63, 2550
1377, 52, 69, 18, 40, 63, 2569 is not bigger than 77.77, 52, 69, 18, 40, 63, 2560
1477, 52, 69, 18, 40, 63, 2577 is at least as big as both its children, so it stops here.77, 52, 69, 18, 40, 63, 2560
1577, 52, 69, 18, 40, 63, 25Every 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, 2560

In all, 6 comparisons. The formula from section 4, n−1n - 1, gives B=6B = 6 at n=7n = 7: 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

numberbeats the top?the 3 kepttop
5, 9, 2the first 32, 5, 92
7yes, 7 beats 25, 7, 95
8yes, 8 beats 57, 8, 97
1no7, 8, 97
Python's nlargest on 5, 9, 2, 7, 8, 1, keeping the 3 biggest. Each later number meets the top of the 3 kept.

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 nn numbers, side by side. On shuffled numbers one at a time costs a little more, as section 6 measures. Smallest first sets them apart.

comparisonsone at a timebottom up
fewestn−1n - 1, biggest firstn−1n - 1, a heap already
mostat most n log⁡2 nn \,\log_2\, n, smallest firstat most 2n−22n - 2
growthΘ(n log⁡2 n)\Theta(n \,\log_2\, n), smallest firstΘ(n)\Theta(n), every row
The two ways, counted in comparisons, from section 4.
numbersone at a timebottom up
1534 (2.27)22 (1.47)
3198 (3.16)52 (1.68)
63258 (4.10)114 (1.81)
1,0238,194 (8.01)2,026 (1.98)
Smallest first, in comparisons, per number in brackets. Per number, bottom up stays under 2, while one at a time grows by about 1 each time the numbers double.
102104106108101102103104105106107101102103104105106107108109101102103104105106107
  • one at a time at most, n log⁡2 nn \,\log_2\, n
  • smallest first, one at a time, at least n2(log⁡2 n−2)\frac{n}{2}(\log_2\, n - 2)
  • bottom up at most, 2n−22n - 2
  • bottom up at least, n−1n - 1
On a log-log plot. Bottom up stays between its two lines, one step up for each step across. One at a time on smallest first lies between its own two; the lower is only a floor, and the table above gives the exact counts. Counted exactly, smallest first one at a time costs more than 2n−22n - 2 from 10 numbers on, 19 against 18 at 10. Each later put adds at least 3, the line only 2.