Skip to content

Changing a number in a heap

storing

Level 2 of 3

Also called Decrease-key, Increase-key, Change-key and Priority update.

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.

182740346152181272403344615526
The heap after six puts. Place 1's children are 2 × 1 = 2 and 2 × 1 + 1 = 3; place 2's are 4 and 5; place 3's is 6.
finding 52what it checkslooks
with the notereads 52, place 60
with no noteplaces 1 to 6, in turn6
With the note, finding costs no look and no comparison.
numberbefore9 written at 69 swaps with 409 swaps with 18
181113
272222
403366
344444
615555
526
9631
The note of places as 52 becomes 9. The two swaps rewrite four entries.
One gets smaller, one gets bigger: 7 moments of its 40 steps, the steps between them left for the watch page
  1. step 20 of 40

    123456182740346152b18d27f40a34e61c52

    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

    watch from here

  2. step 21 of 40

    12345618274034619b18d27f40a34e61c9

    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

    watch from here

  3. step 23 of 40

    12345618279346140b18d27c9a34e61f40

    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

    watch from here

  4. step 25 of 40

    12345692718346140c9d27b18a34e61f40

    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

    watch from here

  5. step 28 of 40

    12345697018346140c9d70b18a34e61f40

    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

    watch from here

  6. step 31 of 40

    12345693418706140c9a34b18d70e61f40

    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

    watch from here

  7. step 32 of 40

    12345693418706140c9a34b18d70e61f40

    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

    watch from here

the steps, in plain words
  1. start with an empty heap: a row read as a tree, smallest on topPython lines 9 and 10
  2. to put a number in, add it at the end of the rowPython lines 65, 66 and 67
  3. while it is smaller than the number above it, swap themPython lines 22, 23, 24, 25, 26, 27, 28 and 68
  4. to take one out, take the smallest, from the topPython lines 42 and 44
  5. move the last number to the topPython lines 45, 46, 47, 48 and 49
  6. 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
  7. an empty heap has nothing to takePython line 43
  8. 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
  9. if it got smaller, while it is smaller than the number above it, swap themPython lines 59, 60, 61 and 62
  10. if not, while a number below it is smaller, swap it with the smaller of themPython lines 63 and 64
  11. 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' n−1n - 1: 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 ⌊log⁡2 n⌋\lfloor \log_2\, n \rfloor a change: 3 for 10, 9 for 1,000.

comparisons, ten times more at each mark up

a secondslope 1.1102104106108101102103104105106107a secondslope 1.1101102103104105106107108109101102103104105106107a secondslope 1.1101102103104105106107108109101102103104105106107

nn, 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
what a dearest row costs, at a billion comparisons a second
nncomparisonstime
1,0009,999about 10 microseconds
100,0001,699,999about 1.7 milliseconds
10,000,000239,999,999about 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.

what each case costs, and how fast that cost grows; section 4 works out every formula in it
besteach change makes the top smaller, the same place every timeaverageeach change makes a number picked at random the smallest; the average over every pickworsteach change makes the number at the last place the smallest
comparisonsn−1n - 1, the puts alonen−1n - 1 for the puts, plus ⌊log⁡2 1⌋+⋯+⌊log⁡2 n⌋\lfloor \log_2\, 1 \rfloor + \dots + \lfloor \log_2\, n \rfloor; at 4, 3 + 0 + 1 + 1 + 2 = 7(n−1)+n⌊log⁡2 n⌋(n - 1) + n\lfloor \log_2\, n \rfloor
swaps0, nothing climbs⌊log⁡2 1⌋+⋯+⌊log⁡2 n⌋\lfloor \log_2\, 1 \rfloor + \dots + \lfloor \log_2\, n \rfloorn⌊log⁡2 n⌋n\lfloor \log_2\, n \rfloor
how the comparisons grow in each case
tight, Θ\ThetaΘ(n)\Theta(n)Θ(n log⁡2 n)\Theta(n \,\log_2\, n)Θ(n log⁡2 n)\Theta(n \,\log_2\, n)
ceiling, OOO(n)O(n)O(n log⁡2 n)O(n \,\log_2\, n)O(n log⁡2 n)O(n \,\log_2\, n)
floor, Ω\OmegaΩ(n)\Omega(n)Ω(n log⁡2 n)\Omega(n \,\log_2\, n)Ω(n log⁡2 n)\Omega(n \,\log_2\, n)

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.

numbersput inthe changes write
23, 42, 1
34, 5, 63, 2, 1
45, 6, 7, 84, 3, 2, 1
The job for 2, 3 and 4 numbers. Each change writes a number smaller than every number held.
numberspickscheapestaveragedearest
24123
327245
42563711
53,12541014
646,65651317
Every pick tried, in comparisons; each of nn changes picks one of nn numbers, 4 × 4 × 4 × 4 = 256 picks at 4.
  • 5261740

    8 made 4 climbs to the top, 2 comparisons

  • 5677

    8 made 7 stops at once, 1 comparison

The heap 5, 6, 7, 8, just after its 8 is changed. Made the smallest, it climbs to the top; made a little smaller, it stops.

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.

Why do nn changes at the top cost only the puts' n−1n - 1 comparisons, the fewest any nn puts can?
  1. the move: count the puts

    the line:
    each put after the firstcompares once, then stays\begin{gathered} \text{each put after the first} \\ \text{compares once, then stays} \end{gathered}
    operationcomparisons
    put 50
    put 6, 7 and 83
    5 to 4, at the top0
    4 to 3, 3 to 2, 2 to 10
    in all3
    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.

  2. the move: a change at the top

    the line:
    a change at the topcompares nothing\begin{gathered} \text{a change at the top} \\ \text{compares nothing} \end{gathered}
    1. step 10 of 22

      5678

      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

    2. step 11 of 22

      4678

      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

    3. step 12 of 22

      4678

      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.

  3. the move: add them

    the line:
    B=(n−1)+n×0B = (n - 1) + n \times 0

    why it is allowed: BB is the comparisons when every change is at the top. By line 1, n−1n - 1 for the puts; by line 2, none for each of the nn changes.

  4. the move: tidy

    the line:
    B=n−1B = n - 1

    why it is allowed: For 4, 3, as in the picture.

  5. the move: nothing costs fewer

    the line:
    n puts in a rowinto an empty heapcompare at least this\begin{gathered} n \text{ puts in a row} \\ \text{into an empty heap} \\ \text{compare at least this} \end{gathered}

    why it is allowed: A put into a heap that is not empty compares at least once. Changes add 0 or more.

  6. the move: a ceiling

    the line:
    B≤nB \le n

    why it is allowed: By line 4, 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: By line 4, as half of nn is at most n−1n - 1 from 2 on. At 4, 2 is under 3.

  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=4n = 4, line 3 gives B=3B = 3, which you can work out by hand

At most how many comparisons can a change made smaller cost, and which nn changes cost the most?
  1. the move: a number made smaller climbs

    the line:
    a number made smaller climbs:a comparison that finds itsmaller swaps it up a level;one that does not stops it\begin{gathered} \text{a number made smaller climbs:} \\ \text{a comparison that finds it} \\ \text{smaller swaps it up a level;} \\ \text{one that does not stops it} \end{gathered}
    1. step 10 of 17

      5678

      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

    2. step 13 of 17

      5476

      Swap them: 4 climbs above 6.

      comparisons: 1

    3. step 15 of 17

      4576

      Swap them: 4 climbs above 5.

      comparisons: 2

    4. step 16 of 17

      4576

      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.

  2. the move: made the smallest, it goes to the top

    the line:
    made smaller than every number,a change at place p costsits levels to the top\begin{gathered} \text{made smaller than every number,} \\ \text{a change at place } p \text{ costs} \\ \text{its levels to the top} \end{gathered}

    why it is allowed: Each comparison finds it smaller, so each one swaps.

  3. the move: change the last place each time

    the line:
    W=(n−1)+n×levelsfrom place n to the top\begin{gathered} W = (n - 1) + n \times \text{levels} \\ \text{from place } n \text{ to the top} \end{gathered}
    • 5261780

      8 to 4, 2 comparisons

    • 4251760

      6 to 3, 2 comparisons

    • 3241750

      5 to 2, 2 comparisons

    • 2231740

      4 to 1, 2 comparisons

    • 1273

      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: WW is the comparisons when each change makes the number at the last place the smallest. The puts make n−1n - 1, by line 1 of the question on the cheapest job. Each change climbs from place nn, by line 2.

  4. the move: name the levels

    the line:
    W=(n−1)+n⌊log⁡2 n⌋W = (n - 1) + n\lfloor \log_2\, n \rfloor
    where does this come from?
    question 3 of the page trees and their wordsA tree of nn places kept in a row. What is its height?
    1. the move: the last place is the deepest

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

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

    2. the move: each step up halves

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

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

    3. the move: count the steps

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

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

    4. the move: use halving and logarithms

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

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

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

      2. the move: rounding down never adds

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

      8. the move: halve both sides of line 5

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

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

      9. the move: write the half as a power

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

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

      10. the move: round the half down

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

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

      11. the move: halve both sides of line 7

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

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

      12. the move: write the half as a power

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

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

      13. the move: round the half down

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

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

      14. the move: take the log of line 10

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

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

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

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

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

      16. the move: take the log of line 13

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

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

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

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

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

      18. the move: round the log down

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

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

      19. the move: use line 18 again and again

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

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

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

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

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

      the whole page: halving and logarithms

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

    5. the move: read it

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

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

    the whole page: trees and their words

    why it is allowed: The box under this line shows that the last place lies ⌊log⁡2 n⌋\lfloor \log_2\, n \rfloor levels below the top. For 4, 3 for the puts + 4 × 2 = 11.

  5. the move: the changes alone

    the line:
    W−(n−1)=n⌊log⁡2 n⌋W - (n - 1) = n\lfloor \log_2\, n \rfloor

    why it is allowed: By line 4, taking away the puts' n−1n - 1. For 4, 8.

  6. the move: count the swaps

    the line:
    the dearest job makesn⌊log⁡2 n⌋ swaps\begin{gathered} \text{the dearest job makes} \\ n\lfloor \log_2\, n \rfloor \text{ swaps} \end{gathered}

    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.

  7. the move: no change made smaller costs more

    the line:
    a change at place p costs at most⌊log⁡2 p⌋, no more than ⌊log⁡2 n⌋\begin{gathered} \text{a change at place } p \text{ costs at most} \\ \lfloor \log_2\, p \rfloor \text{, no more than } \lfloor \log_2\, n \rfloor \end{gathered}
    • 5261740

      8 made 4 climbs 2 levels, 2 comparisons

    • 14382530

      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.
    depth012011222201121324252627012
    Each place pp of a heap of 7 shows ⌊log⁡2 p⌋\lfloor \log_2\, p \rfloor, its levels to the top.

    why it is allowed: Place pp is the last place of a heap of pp places. So by the box under line 4, with pp for nn, it lies ⌊log⁡2 p⌋\lfloor \log_2\, p \rfloor levels down, no deeper than place nn. An early stop costs no more; see the pictures.

  8. the move: no job of changes made smaller costs more

    the line:
    so no n changes madesmaller cost more than W\begin{gathered} \text{so no } n \text{ changes made} \\ \text{smaller cost more than } W \end{gathered}

    why it is allowed: By line 7, after these puts each change costs at most the last place's climb, which line 4 counts nn times.

  9. the move: drop the rounding

    the line:
    W≤(n−1)+n log⁡2 nW \le (n - 1) + n\,\log_2\, n

    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.

  10. the move: put n log⁡2 nn\,\log_2\, n for n−1n - 1

    the line:
    W≤n log⁡2 n+n log⁡2 nW \le n\,\log_2\, n + n\,\log_2\, n

    why it is allowed: From 2 on, log⁡2 n\log_2\, n is at least 1, so n−1n - 1 is less than n log⁡2 nn\,\log_2\, n. At 4, 3 is less than 8.

  11. the move: add them

    the line:
    W≤2n log⁡2 nW \le 2n\,\log_2\, n

    why it is allowed: At 4, 2 × 4 × 2 is 16, above 11.

  12. the move: read it as a bound

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

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

  13. the move: a floor

    the line:
    W≥n⌊log⁡2 n⌋W \ge n\lfloor \log_2\, n \rfloor

    why it is allowed: By line 5, as the puts cost 0 or more.

  14. the move: rounding down keeps half

    the line:
    W≥n log⁡2 n2 for n≥2W \ge \frac{n \,\log_2\, n}{2} \text{ for } n \ge 2
    numberslog⁡2 n\log_2\, nrounded downhalf
    2110.5
    31.5810.79
    4221
    72.8121.4
    8331.5
    Rounded down, the log never falls below half of itself from 2 on.

    why it is allowed: While log⁡2 n\log_2\, n 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.

  15. the move: read it as a bound

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

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

  16. the move: ceiling and floor together

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

    why it is allowed: Lines 11 and 14 bound WW by the same growth, n log⁡2 nn \,\log_2\, n.

try it with a small nn: at n=4n = 4, line 3 gives W=11W = 11, which you can work out by hand

One change made smaller, in a heap of nn. Why is its dearest Θ(log⁡2 n)\Theta(\log_2\, n)?
  1. the move: the dearest change made smaller

    the line:
    h=⌊log⁡2 n⌋h = \lfloor \log_2\, n \rfloor
    numbershhaverage a changelog⁡2 n\log_2\, n
    4212
    1031.93.32
    1,00097.999.97
    1,000,0001917.9519.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 hh. The last place's number made the smallest climbs all of them, by line 2 there. For 4, 2.

  2. the move: a ceiling

    the line:
    h≤log⁡2 nh \le \log_2\, n

    why it is allowed: By line 1, as rounding down never makes a number bigger.

  3. the move: a floor

    the line:
    h≥log⁡2 n2 for n≥2h \ge \frac{\log_2\, n}{2} \text{ for } n \ge 2

    why it is allowed: By line 1, as rounding down keeps at least half, by line 14 of the question on the dearest job.

  4. the move: ceiling and floor together

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

    why it is allowed: Lines 2 and 3 bound hh by the same growth.

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

One change that makes a number bigger. At most how many comparisons?
  1. the move: a number made bigger sinks

    the line:
    a number made no smallersinks\begin{gathered} \text{a number made no smaller} \\ \text{sinks} \end{gathered}

    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.

  2. the move: price a round

    the line:
    a round compares each childwith the smaller so far,then swaps or stops\begin{gathered} \text{a round compares each child} \\ \text{with the smaller so far,} \\ \text{then swaps or stops} \end{gathered}
    1. step 22 of 31

      8331970452652

      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

    2. step 26 of 31

      19339070452652

      Swap them: 90 sinks below 19.

      comparisons: 2

    3. step 29 of 31

      19332670459052

      Swap them: 90 sinks below 26.

      comparisons: 4

    4. step 30 of 31

      19332670459052

      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.
    roundcomparesthen
    133 with 90, 19 with 33swap 90 with 19
    226 with 90, 52 with 26swap 90 with 26
    no roundno child below 90it 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.

  3. the move: count the rounds

    the line:
    D=2⌊log⁡2 n⌋D = 2\lfloor \log_2\, n \rfloor

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

  4. the move: drop the rounding

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

    why it is allowed: By line 3, as rounding down never makes a number bigger.

  5. the move: read it as a bound

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

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

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

Each change picks a number at random and makes it the smallest. Why do nn such changes cost Θ(n log⁡2 n)\Theta(n \,\log_2\, n) on average?
  1. the move: every place as likely

    the line:
    each place is pickedwith chance 1n\begin{gathered} \text{each place is picked} \\ \text{with chance } \frac{1}{n} \end{gathered}
    first changesecond changecomparisons
    the topthe top1
    the topplace 22
    place 2the top2
    place 2place 23
    average2
    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.

  2. the move: add up the places

    the line:
    A=(n−1)+n(c(1)×1n+⋯+c(n)×1n)\begin{aligned} A = {} & (n - 1) \\ & + n\bigl(c(1) \times \tfrac{1}{n} + \dots + c(n) \times \tfrac{1}{n}\bigr) \end{aligned}
    placelevels to the top
    10
    21
    31
    42
    in all4
    A heap of 4. A change averages 4 times a quarter, which is 1, and four changes give 4.

    why it is allowed: AA is the average comparisons, and c(p)c(p) the climb from place pp. The puts make n−1n - 1. By line 1, a change averages each climb times 1n\frac{1}{n}. Averages add, by line 2 of question 2 of the page expected cost, so nn changes give nn times that.

  3. the move: cancel

    the line:
    A=(n−1)+c(1)+⋯+c(n)A = (n - 1) + c(1) + \dots + c(n)

    why it is allowed: By line 2, as nn times 1n\frac{1}{n} is 1. For 4, 3 + 0 + 1 + 1 + 2 is 7, the average over all 256 picks.

  4. the move: name the levels

    the line:
    A=(n−1)+⌊log⁡2 1⌋+⋯+⌊log⁡2 n⌋\begin{aligned} A = {} & (n - 1) \\ & + \lfloor \log_2\, 1 \rfloor + \dots + \lfloor \log_2\, n \rfloor \end{aligned}

    why it is allowed: By line 2 of the question on the dearest job, c(p)c(p) is place pp's levels, ⌊log⁡2 p⌋\lfloor \log_2\, p \rfloor by line 7 of that question.

  5. the move: the changes alone

    the line:
    A−(n−1)=⌊log⁡2 1⌋+⋯+⌊log⁡2 n⌋\begin{aligned} A - (n - 1) = {} & \lfloor \log_2\, 1 \rfloor \\ & + \dots + \lfloor \log_2\, n \rfloor \end{aligned}

    why it is allowed: By line 4, taking away the puts' n−1n - 1. For 4, 4.

  6. the move: count the swaps

    the line:
    on average the changes swap⌊log⁡2 1⌋+⋯+⌊log⁡2 n⌋times\begin{gathered} \text{on average the changes swap} \\ \lfloor \log_2\, 1 \rfloor + \dots + \lfloor \log_2\, n \rfloor \\ \text{times} \end{gathered}

    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.

  7. the move: count level by level

    the line:
    A=(n−1)+(n−2+1)+(n−4+1)+…+(n−2h+1)\begin{aligned} A = (n - 1) &+ (n - 2 + 1) \\ &+ (n - 4 + 1) + \dots \\ &+ (n - 2^h + 1) \end{aligned}
    • 0112222

      1 down or more, 6 places

    • 0112222

      2 down or more, 4 places

    A heap of 7, each place showing its levels, 10 in all.
    place1 down or more2 down or morelevels
    1000
    2101
    3101
    4112
    5112
    6112
    7112
    in all6410
    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 kk starts at place 2 to the power kk. 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 pp for nn. So the places at least kk down run from there to nn.

  8. the move: gather

    the line:
    A=(n−1)+h(n+1)−(2+4+⋯+2h)\begin{aligned} A = {} & (n - 1) + h(n + 1) \\ & - (2 + 4 + \dots + 2^h) \end{aligned}

    why it is allowed: Each of the hh brackets holds n+1n + 1, less a power of 2. For 4, hh is 2, and 3 + 2 × 5, less 2 + 4, is 7.

  9. the move: add 1 and take it away

    the line:
    A=(n−1)+h(n+1)−((1+2+⋯+2h)−1)\begin{aligned} A = {} & (n - 1) + h(n + 1) \\ & - \bigl((1 + 2 + \dots + 2^h) - 1\bigr) \end{aligned}

    why it is allowed: This changes nothing, and the bracket now starts at 1. For 4, 2 + 4 is 1 + 2 + 4, less 1.

  10. the move: use the doubling sum, h for n

    the line:
    A=(n−1)+h(n+1)−((2h+1−1)−1)\begin{aligned} A = {} & (n - 1) + h(n + 1) \\ & - \bigl((2^{h + 1} - 1) - 1\bigr) \end{aligned}
    where does this come from?
    question 1 of the page doubling and halving sumsAdd 1+2+4+⋯+2n1 + 2 + 4 + \dots + 2^n. What is the total?
    1. the move: name the sum

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

      why it is allowed: Let SS be the doubling sum up to 2n2^n. For nn as 3, it is 1 + 2 + 4 + 8.

    2. the move: double both sides

      the line:
      2S=2+4+8+⋯+2n+12S = 2 + 4 + 8 + \dots + 2^{n + 1}

      why it is allowed: Each term doubled is the next one along, and 2n2^n becomes 2n+12^{n + 1}. Doubling both sides keeps them equal. The plan: the two sums share all but their ends.

    3. the move: take line 1 away

      the line:
      2S−S=(2+4+⋯+2n+1)−(1+2+⋯+2n)\begin{aligned} 2S - S = {} & (2 + 4 + \dots + 2^{n + 1}) \\ & - (1 + 2 + \dots + 2^n) \end{aligned}

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

    4. the move: tidy the left side

      the line:
      S=(2+4+⋯+2n+1)−(1+2+⋯+2n)\begin{aligned} S = {} & (2 + 4 + \dots + 2^{n + 1}) \\ & - (1 + 2 + \dots + 2^n) \end{aligned}

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

    5. the move: cancel what both brackets share

      the line:
      S=2n+1−1S = 2^{n + 1} - 1
      when n is 3124816
      first bracket24816
      second bracket1248
      left overtake away 116
      Line 4 when nn is 3. The 2, 4 and 8 cancel, leaving 16 less 1, which is 15.

      why it is allowed: Every term from 2 to 2n2^n is in both brackets and cancels, leaving 2n+12^{n + 1} less 1.

    6. the move: the terms before the last

      the line:
      1+2+⋯+2n−1=2(n−1)+1−1\begin{gathered} 1 + 2 + \dots + 2^{n - 1} \\ = 2^{(n - 1) + 1} - 1 \end{gathered}

      why it is allowed: The sum of line 5 stopping one term sooner: line 5 with n−1n - 1 for nn. For 3, it is 1 + 2 + 4. At nn as 0 no terms are left, adding to 0, and 2 to the power 0, less 1, is 0 too.

    7. the move: tidy the power

      the line:
      2(n−1)+1−1=2n−12^{(n - 1) + 1} - 1 = 2^n - 1

      why it is allowed: One more than n−1n - 1 is nn. For 3, 1 + 2 + 4 is 7, one less than 8.

    8. the move: read it

      the line:
      one less thanthe next term,under twice the last\begin{gathered} \text{one less than} \\ \text{the next term,} \\ \text{under twice the last} \end{gathered}

      why it is allowed: By lines 6 and 7, the terms before the last add to one less than it: the last outweighs them all. By line 5 the sum is under 2n+12^{n + 1}, twice the last.

    the whole page: doubling and halving sums

    why it is allowed: The box under this line shows a doubling sum from 1 is one less than its next term. For 4, 1 + 2 + 4 is 7, one less than 8.

  11. the move: take away its 1

    the line:
    A=(n−1)+h(n+1)−(2h+1−2)\begin{aligned} A = {} & (n - 1) + h(n + 1) \\ & - (2^{h + 1} - 2) \end{aligned}

    why it is allowed: One less, then 1 less again, is two less. For 4, 2 + 4 is 6.

  12. the move: tidy

    the line:
    A=(n−1)+(n+1)h−2h+1+2A = (n - 1) + (n + 1)h - 2^{h + 1} + 2

    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.

  13. the move: a ceiling from the dearest job

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

    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.

  14. the move: read it as a bound

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

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

  15. the move: the last level starts in the row

    the line:
    A≥(n−1)+(n+1)h−2n+2A \ge (n - 1) + (n + 1)h - 2n + 2

    why it is allowed: Now a floor, AA above a fixed part of n log⁡2 nn \,\log_2\, n. By line 12. 2h2^h is at most nn, by line 5 of the box on halving inside the box under line 4 of the question on the dearest job. So 2h+12^{h + 1} is at most 2n2n, and taking away 2n2n takes at least as much. At 6, AA is 13 and the right side 9.

  16. the move: gather

    the line:
    A≥(n+1)h−n+1A \ge (n + 1)h - n + 1

    why it is allowed: n−1n - 1, less 2n2n, plus 2, leaves 1 minus nn. At 6, 7 × 2, less 6, plus 1, is 9.

  17. the move: drop what is left over

    the line:
    A≥n(h−1)A \ge n(h - 1)

    why it is allowed: Line 16 is n(h−1)n(h - 1) plus h+1h + 1, which is more than 0. At 6, 6 × 1 + 3 is 9.

  18. the move: a quarter of h + 1

    the line:
    A≥n(h+1)4 for n≥4A \ge \frac{n(h + 1)}{4} \text{ for } n \ge 4

    why it is allowed: From 4 on, hh is at least 2, and a quarter of h+1h + 1 is at most h−1h - 1. With hh at 2, three quarters against 1; each 1 more on hh adds a quarter to the first and 1 to the second.

  19. the move: a simpler floor

    the line:
    A≥n log⁡2 n4 for n≥4A \ge \frac{n \,\log_2\, n}{4} \text{ for } n \ge 4

    why it is allowed: log⁡2 n\log_2\, n is less than h+1h + 1. At 4, lines 19, 18 and 17 give 2, 3 and 4, and AA is 7.

  20. the move: read it as a bound

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

    why it is allowed: By line 19, with the fixed multiple a quarter.

  21. the move: ceiling and floor together

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

    why it is allowed: Lines 13 and 19 bound AA by the same growth, n log⁡2 nn \,\log_2\, n, with the fixed multiples 2 and a quarter.

try it on small inputs: over every pick of 4 changes, 256 in all, the average is A=7A = 7

With no note of places, what does finding the numbers cost?
  1. the move: look along the row

    the line:
    with no note, a changelooks at each place from 1until the number:place p costs p looks\begin{gathered} \text{with no note, a change} \\ \text{looks at each place from 1} \\ \text{until the number:} \\ \text{place } p \text{ costs } p \text{ looks} \end{gathered}
    look forplacelooks
    511
    622
    733
    844
    each once10
    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.

  2. the move: n changes at random

    the line:
    F=n×(1×1n+2×1n+⋯+n×1n)F = n \times \bigl(1 \times \frac{1}{n} + 2 \times \frac{1}{n} + \dots + n \times \frac{1}{n}\bigr)

    why it is allowed: FF is the average looks of nn 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.

  3. the move: use the page on what a structure promises

    the line:
    F=n×n+12F = n \times \frac{n + 1}{2}
    where does this come from?
    question 3 of the page what a structure promisesA dictionary kept as an unsorted row of nn keys. Look up a key that is there, equally likely to be at any place. How many looks, on average?
    1. the move: one look up

      the line:
      the key at place kcosts k looks\begin{gathered} \text{the key at place } k \\ \text{costs } k \text{ looks} \end{gathered}
      look upplacelooks
      1711
      4222
      833
      2244
      all four10
      35, not there4
      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 kk is the place of the key you want, so places 1 to kk cost kk looks. A key that is not there costs a look at every key: nn looks.

    2. the move: each place times its chance

      the line:
      L=∑k=1nk×1nL = \sum_{k=1}^{n} k \times \frac{1}{n}

      why it is allowed: Let LL be the average. Σ\Sigma means add up: the term after it, once for each kk from the 1 under it to the nn over it. With 4 keys each place has chance 1 over 4. So LL adds 1, 2, 3 and 4 looks, each times 1 over 4: 10 over 4, which is 2.5, the table's average. With nn keys each chance is 1 over nn, and by line 1 the key at place kk costs kk looks.

    3. the move: use the page on expected cost

      the line:
      L=n+12L = \frac{n + 1}{2}
      where does this come from?
      question 1 of the page expected costPick a whole number from 1 to nn, each as likely. What is its expected value?
      1. the move: each value times its chance

        the line:
        E=∑k=1nk×1nE = \sum_{k=1}^{n} k \times \frac{1}{n}
        kktimes its chance
        11 over 5
        22 over 5
        33 over 5
        44 over 5
        55 over 5
        in all15 over 5, which is 3
        For 5, each number times its chance, 1 over 5.

        why it is allowed: The expected value EE adds each number kk times its chance, 1 over nn. Σ\Sigma, read the sum of, adds the term after it for each kk from the value under it to the value over it.

      2. the move: take the chance out in front

        the line:
        E=1n∑k=1nkE = \frac{1}{n} \sum_{k=1}^{n} k

        why it is allowed: Each term is multiplied by 1 over nn, so multiply once, after adding. For 5, 1 over 5 times 15.

      3. the move: use the page on adding up

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

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

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

        2. the move: take two staircases

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

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

        3. the move: fit them into a rectangle

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

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

        4. the move: halve both sides

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

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

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

        why it is allowed: The whole numbers from 1 to nn add up to nn times one more than nn, halved, as the page on adding up 1 to nn works out. For 5, 5 times 6, halved, is 15.

      4. the move: cancel the n

        the line:
        E=n+12E = \frac{n + 1}{2}

        why it is allowed: nn on top and nn underneath cancel, as nn is not zero. For 5, 6 over 2 is 3.

      5. the move: read it

        the line:
        the middle of1 and n\begin{gathered} \text{the middle of} \\ \text{1 and } n \end{gathered}

        why it is allowed: By line 4, halfway between the smallest number, 1, and the biggest, nn: 3 for 5.

      the whole page: expected cost

      why it is allowed: That page works out this same sum, for a number picked from 1 to nn, as n+1n + 1 over 2.

    4. the move: read it

      the line:
      about half the row,on average\begin{gathered} \text{about half the row,} \\ \text{on average} \end{gathered}

      why it is allowed: 1,000 keys cost 500.5 looks on average.

    the whole page: what a structure promises

    why it is allowed: The box under this line works out the bracket, one look up in a row of nn, as n+1n + 1 over 2. For 4, 4 × 2.5 is 10.

  4. the move: tidy

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

    why it is allowed: For 1,000 numbers, 500,500 looks.

  5. the move: a ceiling

    the line:
    F≤n2F \le n^2

    why it is allowed: By line 4, as n+1n + 1 is at most 2n2n.

  6. the move: a floor

    the line:
    F≥n22F \ge \frac{n^2}{2}

    why it is allowed: By line 4, as n+1n + 1 is more than nn.

  7. the move: ceiling and floor together

    the line:
    F∈Θ(n2)F \in \Theta(n^2)

    why it is allowed: Lines 5 and 6 bound FF by the same growth, n2n^2, with the fixed multiples 1 and a half.

try it with a small nn: at n=4n = 4, line 2 gives F=10F = 10, 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.

5, 6, 7, 8, 8->4, 6->3, 5->2, 4->1, every step written down
stepthe rowwhat happenscomparisonsswaps
1Start with an empty heap, and 8 operations to do.00
25Put 5 at the end of the row, in place 1.500
355 is at the top, so it stays.500
45, 6Put 6 at the end of the row, in place 2.5, 600
55, 66 is not smaller than 5, the number above it, so it stays.5, 610
65, 6, 7Put 7 at the end of the row, in place 3.5, 6, 710
75, 6, 77 is not smaller than 5, the number above it, so it stays.5, 6, 720
85, 6, 7, 8Put 8 at the end of the row, in place 4.5, 6, 7, 820
95, 6, 7, 88 is not smaller than 6, the number above it, so it stays.5, 6, 7, 830
105, 6, 7, 88 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, 830
115, 6, 7, 4Change 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, 430
125, 6, 7, 44 is smaller than 6, the number above it.5, 6, 7, 440
135, 4, 7, 6Swap them: 4 climbs above 6.5, 4, 7, 641
145, 4, 7, 64 is smaller than 5, the number above it.5, 4, 7, 651
154, 5, 7, 6Swap them: 4 climbs above 5.4, 5, 7, 652
164, 5, 7, 64 is at the top, so it stays.4, 5, 7, 652
174, 5, 7, 66 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, 652
184, 5, 7, 3Change 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, 352
194, 5, 7, 33 is smaller than 5, the number above it.4, 5, 7, 362
204, 3, 7, 5Swap them: 3 climbs above 5.4, 3, 7, 563
214, 3, 7, 53 is smaller than 4, the number above it.4, 3, 7, 573
223, 4, 7, 5Swap them: 3 climbs above 4.3, 4, 7, 574
233, 4, 7, 53 is at the top, so it stays.3, 4, 7, 574
243, 4, 7, 55 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, 574
253, 4, 7, 2Change 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, 274
263, 4, 7, 22 is smaller than 4, the number above it.3, 4, 7, 284
273, 2, 7, 4Swap them: 2 climbs above 4.3, 2, 7, 485
283, 2, 7, 42 is smaller than 3, the number above it.3, 2, 7, 495
292, 3, 7, 4Swap them: 2 climbs above 3.2, 3, 7, 496
302, 3, 7, 42 is at the top, so it stays.2, 3, 7, 496
312, 3, 7, 44 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, 496
322, 3, 7, 1Change 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, 196
332, 3, 7, 11 is smaller than 3, the number above it.2, 3, 7, 1106
342, 1, 7, 3Swap them: 1 climbs above 3.2, 1, 7, 3107
352, 1, 7, 31 is smaller than 2, the number above it.2, 1, 7, 3117
361, 2, 7, 3Swap them: 1 climbs above 2.1, 2, 7, 3118
371, 2, 7, 31 is at the top, so it stays.1, 2, 7, 3118
381, 2, 7, 3Done. The heap holds 4 numbers.1, 2, 7, 3118

In all, 11 comparisons. The formula from section 4, (n−1)+n⌊log⁡2 n⌋(n - 1) + n\lfloor \log_2\, n \rfloor, gives W=11W = 11 at n=4n = 4: 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

towndistance beforeafter taking C
C5taken, the nearest
B109, by 5 + 4, made smaller
Dnone12, by 5 + 7, put in
A search from A, with roads A to B 10, A to C 5, C to B 4 and C to D 7.
stepthe heap's rowcost
put 3, 9 and 53, 9, 52 comparisons
look for 9, at places 1 and 23, 9, 52 looks
move 5, the last, into place 23, 51 comparison, 5 stays
put 43, 5, 41 comparison, 4 stays
Remove and put back on 3, 9, 5, changing 9 to 4, with no note.
operationthe heap's rowdead
put 3, 9 and 53, 9, 5
9 to 4: put 4, mark 9 dead3, 4, 5, 99
take, giving 34, 9, 59
take, giving 45, 99
take, giving 599
take: 9 is dead, thrown awaynothing
Lazy deletion on 3, 9, 5, changing 9 to 4. The dead 9 waits for a take to reach it.

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.

wayfind the numberthennn changes, each making a number picked at random the smallest
a heap with a noteone read of the note, no comparisonclimb up to ⌊log⁡2 n⌋\lfloor \log_2\, n \rfloor levels, or sink up to 2⌊log⁡2 n⌋2\lfloor \log_2\, n \rfloor comparisonsΘ(n log⁡2 n)\Theta(n \,\log_2\, n), with the puts
a heap with no notea look at each place from 1, n+12\frac{n + 1}{2} on averagethe samen(n+1)2\frac{n(n + 1)}{2} looks more, Θ(n2)\Theta(n^2)
an unsorted rowthe same looksnothing to repairthe same looks; a take then checks all nn numbers for the smallest
a row kept in orderhalving, as binary search does: it looks at the middle of what is leftwalk to its new place, past every number betweenfrom place pp, pp minus 1 steps. Each place as likely, half of n−1n - 1 on average, as n+12\frac{n + 1}{2} less 1, by the box under line 3 of the question with no note. nn changes, nn times that, at most half of n2n^2; from 2 on at least a quarter, as n−1n - 1 is at least half of nn. So Θ(n2)\Theta(n^2): 6 at 4, 499,500 at 1,000
In comparisons and looks, each way holding nn numbers.
10210410610810101012101410110210310410510610710110210310410510610710810910101011101210131014101102103104105106107
  • a heap with a note, the average
  • a heap with no note, the average and n(n+1)2\frac{n(n + 1)}{2} looks
With a note the line climbs a little over one step a step across; with no note, two, as looks grow like n2n^2. At 1,000, 8,986 against 509,486.