Skip to content

AVL tree

storing

Level 3 of 3

Also called Self-balancing binary search tree and Adelson-Velsky and Landis tree.

how it works

The idea in a few sentences and three pictures, then one run, moment by moment.

An AVL tree keeps a search tree short as numbers go in. A number goes in as in the plain tree: start at the top, smaller goes left, bigger goes right, and hang it where the way runs out. Each number met is one comparison, this page's count. Then climb back towards the top, comparing each place's two sides: how many levels each reaches. Where one side is two levels higher, turn there to lift it. A side that leans inwards is turned outwards first, a double turn, which is two turns. Weighing levels compares no numbers, so the climb adds no comparison. A put mends at most once, with a single turn or a double. The turned side gets back the levels it had before the put, so every place above sees what it saw before. Sebastian Bourges' books put it: 'the descent is unchanged, and the repair rides home on the return.' (volume two, chapter 20). The run after these pictures puts in 10, 20, 30, 40, 50, 60 and 70, in order.

  1. step 8 of 14

    1020

    30 is bigger than 10, so go right.

    numbers compared: 1

  2. step 9 of 14

    1020

    30 is bigger than 20, so go right.

    numbers compared: 2

  3. step 10 of 14

    102030

    The way runs out, so hang 30 to the right of 20.

    numbers compared: 2

  4. step 12 of 14

    102030

    At 10, the left side is empty and the right side 2 levels high: two levels apart, so the tree must turn.

    numbers compared: 2

  5. step 13 of 14

    102030

    Turn left at 10: 20 moves up into its place, and 10 hangs to its left.

    numbers compared: 2

Operation 3 puts 30 in. It meets 10 and 20, 2 comparisons, and hangs on level 2. Climbing back, 10's left side is empty and its right 2 levels high. Turn left at 10: 20 moves up.
  1. step 10 of 15

    203040

    The way runs out, so hang 30 to the right of 20.

    numbers compared: 2

  2. step 12 of 15

    203040

    At 40, the left side is 2 levels high and the right side empty: two levels apart, so the tree must turn.

    numbers compared: 2

  3. step 13 of 15

    203040

    Turn left at 20: 30 moves up into its place, and 20 hangs to its left.

    numbers compared: 2

  4. step 14 of 15

    203040

    Turn right at 40: 30 moves up into its place, and 40 hangs to its right.

    numbers compared: 2

30 hangs right of 20, so 40's high side leans inwards. Turn left at 20 first, then right at 40, and 30 ends on top: a double turn. Still 2 comparisons.
  1. step 35 of 37

    102030405060

    At 20, the left side is one level high and the right side 3 levels high: two levels apart, so the tree must turn.

    numbers compared: 3

  2. step 36 of 37

    102030405060

    Turn left at 20: 40 moves up into its place, and 20 hangs to its left.

    numbers compared: 3

After 60 goes in, 20's right side is 3 levels high and its left 1. Turn left at 20: 40 moves up, and 30, between 20 and 40, moves across to hang right of 20.
In order, kept short by turning: 8 moments of its 45 steps, the steps between them left for the watch page
  1. step 10 of 45

    a10b20c30

    The way runs out, so hang 30 to the right of 20.

    what it remembers to know where it is
    doing operation
    3
    looking at
    not yet
    in the tree
    3

    Where it says not yet, nothing is held there at that moment.

    watch from here

  2. step 12 of 45

    a10b20c30

    At 10, the left side is empty and the right side 2 levels high: two levels apart, so the tree must turn.

    what it remembers to know where it is
    doing operation
    3
    looking at
    10
    in the tree
    3

    watch from here

  3. step 13 of 45

    a10b20c30

    Turn left at 10: 20 moves up into its place, and 10 hangs to its left.

    what it remembers to know where it is
    doing operation
    3
    looking at
    not yet
    in the tree
    3

    Where it says not yet, nothing is held there at that moment.

    watch from here

  4. step 26 of 45

    a10b20c30d40e50

    At 30, the left side is empty and the right side 2 levels high: two levels apart, so the tree must turn.

    what it remembers to know where it is
    doing operation
    5
    looking at
    30
    in the tree
    5

    watch from here

  5. step 27 of 45

    a10b20c30d40e50

    Turn left at 30: 40 moves up into its place, and 30 hangs to its left.

    what it remembers to know where it is
    doing operation
    5
    looking at
    not yet
    in the tree
    5

    Where it says not yet, nothing is held there at that moment.

    watch from here

  6. step 35 of 45

    a10b20c30d40e50f60

    At 20, the left side is one level high and the right side 3 levels high: two levels apart, so the tree must turn.

    what it remembers to know where it is
    doing operation
    6
    looking at
    20
    in the tree
    6

    watch from here

  7. step 36 of 45

    a10b20c30d40e50f60

    Turn left at 20: 40 moves up into its place, and 20 hangs to its left.

    what it remembers to know where it is
    doing operation
    6
    looking at
    not yet
    in the tree
    6

    Where it says not yet, nothing is held there at that moment.

    watch from here

  8. step 44 of 45

    a10b20c30d40e50f60g70

    Turn left at 50: 60 moves up into its place, and 50 hangs to its left.

    what it remembers to know where it is
    doing operation
    7
    looking at
    not yet
    in the tree
    7

    Where it says not yet, nothing is held there at that moment.

    watch from here

the steps, in plain words
  1. start with an empty treePython line 50
  2. start at the topPython line 52
  3. smaller goes left, bigger goes right, until the way runs outPython lines 53, 54, 55 and 56
  4. hang the number there; a number already in is not put in againPython lines 57, 58, 59, 60, 61, 62, 63, 64, 65, 66 and 67
  5. climb back towards the top, comparing each place's two sidesPython lines 11, 12, 13, 16, 17, 18, 68, 69, 70, 71, 72 and 73
  6. where one side is two levels higher, turn there to lift itPython lines 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 74, 77, 78, 81, 82, 83, 84, 85, 86, 87 and 88
  7. if that side leans inwards, turn it outwards firstPython lines 75, 76, 79 and 80
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.

class Place:
    """One place of the tree: a number, a place on each side, its levels."""

    def __init__(self, value):
        self.value = value  # the number it holds
        self.left = None  # the smaller numbers hang here
        self.right = None  # the bigger numbers hang here
        self.levels = 1  # levels from here down, this one included


def levels(place):
    """How many levels hang from this place, itself included; 0 for none."""
    return 0 if place is None else place.levels


def mend(place):
    """Work out a place's levels again from its two sides."""
    place.levels = 1 + max(levels(place.left), levels(place.right))


def turn(place, way):
    """Turn at this place, 'left' or 'right': its child on the other side
    moves up, and this place hangs below that child. Returns the child."""
    if way == 'right':
        up = place.left
        place.left, up.right = up.right, place
    else:
        up = place.right
        place.right, up.left = up.left, place
    mend(place)  # the lower place first: the upper one reads its levels
    mend(up)
    return up


def shape(place):
    """The tree from this place down, as [left, number, right]."""
    if place is None:
        return None
    return [shape(place.left), place.value, shape(place.right)]


def avl_tree(numbers):
    """Put each number into an AVL tree, in turn.

    Returns the tree as [left, number, right], each side the same shape,
    None where nothing hangs. A number already in is not put in again.
    Each comparison weighs the number at one place against the number put
    in; comparing two sides' levels is no comparison of numbers.
    """
    top = None  # an empty tree
    for number in numbers:
        path, place = [], top  # start at the top
        while place is not None and place.value != number:  # one comparison
            went_left = number < place.value  # smaller goes left
            path.append((place, went_left))
            place = place.left if went_left else place.right
        if place is not None:  # already in: nothing changes
            continue
        child = Place(number)  # hang it where the way ran out
        if not path:
            top = child
            continue
        parent, went_left = path[-1]
        if went_left:
            parent.left = child
        else:
            parent.right = child
        for depth in range(len(path) - 1, -1, -1):  # climb back to the top
            place = path[depth][0]
            lean = levels(place.left) - levels(place.right)
            if abs(lean) < 2:  # the two sides are within one level
                mend(place)
                continue
            if lean == 2:  # the left side is two levels higher
                if levels(place.left.right) > levels(place.left.left):
                    place.left = turn(place.left, 'left')  # leans inwards
                lifted = turn(place, 'right')
            else:  # the right side is two levels higher
                if levels(place.right.left) > levels(place.right.right):
                    place.right = turn(place.right, 'right')  # leans inwards
                lifted = turn(place, 'left')
            if depth == 0:
                top = lifted
            elif path[depth - 1][1]:
                path[depth - 1][0].left = lifted
            else:
                path[depth - 1][0].right = lifted
            break  # one turn, single or double, mends the whole tree
    return shape(top)

how it scales

How the comparisons grow, from ten numbers to a hundred thousand, each put into an empty tree one at a time. Two orders: middle first, level by level, and a shuffle. The plot and tables call a comparison a number compared, as the watch page does.

Each step across or up is ten times the one before, a log-log plot. Both orders climb a little more than one step up for each step across: 480 and about 539 comparisons at 100 numbers, 7,987 and about 8,723 at 1,000. 480 to 7,987 is about 17 times, and the factor shrinks further right. Near 100 to 1,000 numbers, a shuffle costs about a tenth more than middle first, and less further right. Each shuffle point is the mean of 20 shuffles. No formula is worked out for the average, so it is drawn as points only.

numbers compared, ten times more at each mark up

a secondslope 1.1102104106108101102103104105106107a secondslope 1.1101102103104105106107108109101102103104105106107a secondslope 1.1101102103104105106107108109101102103104105106107

nn, how many numbers are in the tree, ten times more at each mark to the right

  • a shuffle, every order as likelypoints only, each measured by a real run, since no single formula for the numbers compared of this row is worked out here
  • middle first, level by level, the cheapest order foundsolid where measured by running it; dashed where its formula carries it on to ten millionslope 1.1: ten times n, about 12 times the work
what numbers put in middle first, level by level, cost, at a billion comparisons a second
nnnumbers comparedtime
1,0007,987about 8 microseconds
100,0001,468,946about 1.5 milliseconds
10,000,000213,222,809about 213 milliseconds

The numbers compared 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 an AVL tree's comparisons yourself, as the plot on this page does.

Run it with Python 3.12 or later. For each size n it puts n different
numbers into an empty tree, one at a time, and prints the comparisons for
the middle first, level by level (the cheapest order found), for 1 to n in
order, and the average over 20 shuffles. A comparison weighs the number at
one place against the number put in; comparing two sides' levels is not
one. The counts are the same on any computer; only the time differs.
"""
import random


class Counted:
    """A number that counts the comparisons made with it."""

    comparisons = 0

    def __init__(self, value):
        self.value = value

    def __ne__(self, other):
        Counted.comparisons += 1  # is this the number? one comparison
        return self.value != other.value

    def __lt__(self, other):
        return self.value < other.value  # which way: part of the same one


class Place:
    """One place of the tree: a number, a place on each side, its levels."""

    def __init__(self, value):
        self.value = value  # the number it holds
        self.left = None  # the smaller numbers hang here
        self.right = None  # the bigger numbers hang here
        self.levels = 1  # levels from here down, this one included


def levels(place):
    """How many levels hang from this place, itself included; 0 for none."""
    return 0 if place is None else place.levels


def mend(place):
    """Work out a place's levels again from its two sides."""
    place.levels = 1 + max(levels(place.left), levels(place.right))


def turn(place, way):
    """Turn at this place, 'left' or 'right': its child on the other side
    moves up, and this place hangs below that child. Returns the child."""
    if way == 'right':
        up = place.left
        place.left, up.right = up.right, place
    else:
        up = place.right
        place.right, up.left = up.left, place
    mend(place)  # the lower place first: the upper one reads its levels
    mend(up)
    return up


def shape(place):
    """The tree from this place down, as [left, number, right]."""
    if place is None:
        return None
    return [shape(place.left), place.value, shape(place.right)]


def avl_tree(numbers):
    """Put each number into an AVL tree, in turn.

    Returns the tree as [left, number, right], each side the same shape,
    None where nothing hangs. A number already in is not put in again.
    Each comparison weighs the number at one place against the number put
    in; comparing two sides' levels is no comparison of numbers.
    """
    top = None  # an empty tree
    for number in numbers:
        path, place = [], top  # start at the top
        while place is not None and place.value != number:  # one comparison
            went_left = number < place.value  # smaller goes left
            path.append((place, went_left))
            place = place.left if went_left else place.right
        if place is not None:  # already in: nothing changes
            continue
        child = Place(number)  # hang it where the way ran out
        if not path:
            top = child
            continue
        parent, went_left = path[-1]
        if went_left:
            parent.left = child
        else:
            parent.right = child
        for depth in range(len(path) - 1, -1, -1):  # climb back to the top
            place = path[depth][0]
            lean = levels(place.left) - levels(place.right)
            if abs(lean) < 2:  # the two sides are within one level
                mend(place)
                continue
            if lean == 2:  # the left side is two levels higher
                if levels(place.left.right) > levels(place.left.left):
                    place.left = turn(place.left, 'left')  # leans inwards
                lifted = turn(place, 'right')
            else:  # the right side is two levels higher
                if levels(place.right.left) > levels(place.right.right):
                    place.right = turn(place.right, 'right')  # leans inwards
                lifted = turn(place, 'left')
            if depth == 0:
                top = lifted
            elif path[depth - 1][1]:
                path[depth - 1][0].left = lifted
            else:
                path[depth - 1][0].right = lifted
            break  # one turn, single or double, mends the whole tree
    return shape(top)


def cheapest(n):
    """1 to n, middle first, level by level: every stretch of a level split
    at its middle, left to right, before the next level starts."""
    order, stretches = [], [(1, n)]
    for low, high in stretches:  # the list grows as it is read
        if low > high:
            continue
        middle = (low + high) // 2
        order.append(middle)
        stretches += [(low, middle - 1), (middle + 1, high)]
    return order


def count(numbers):
    """How many comparisons the tree makes putting these numbers in, in turn."""
    Counted.comparisons = 0
    avl_tree([Counted(number) for number in numbers])
    return Counted.comparisons


if __name__ == "__main__":
    random.seed(1)
    print(f"{'n':>6} {'middle first':>13} {'in order':>10} {'shuffled':>10}")
    for n in [10, 100, 1000]:
        row = list(range(1, n + 1))
        shuffles = []
        for _ in range(20):
            random.shuffle(row)
            shuffles.append(count(row))
        print(f"{n:>6} {count(cheapest(n)):>13} {count(range(1, n + 1)):>10} {sum(shuffles) / 20:>10.1f}")

best, worst and average

A put meets one number on each level above where it hangs, and the turns keep every tree short. So the order barely moves the cost. Middle first, level by level, is the cheapest order found. Every order of 1 to 8 numbers was tried, 46,233 in all, and none costs less. There is no worst column: this page finds the dearest order only by trying every order of short rows. Section 4 bounds every order.

A case is one kind of input, the thing the method is given, such as numbers in order, however many. A bound says how fast that case's cost grows as more numbers go in.

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
bestmiddle first, level by level, the cheapest order foundaveragea shuffle, every order as likely
numbers compared(n+1)L−2L+1+2(n + 1)L - 2^{L + 1} + 2, with LL the log⁡2 n\log_2\, n rounded down: 480 for 100measured, between n log⁡2 n8\frac{n \,\log_2\, n}{8} and 2n log⁡2 n2n \,\log_2\, n: at 100, between about 83 and 1,329, and about 539 measured
how the numbers compared grow in each case
tight, Θ\ThetaΘ(n log⁡2 n)\Theta(n \,\log_2\, n)Θ(n log⁡2 n)\Theta(n \,\log_2\, n)
ceiling, OOO(n log⁡2 n)O(n \,\log_2\, n)O(n log⁡2 n)O(n \,\log_2\, n)
floor, Ω\OmegaΩ(n log⁡2 n)\Omega(n \,\log_2\, n)Ω(n log⁡2 n)\Omega(n \,\log_2\, n)

extra memory: two links and its levels beside each number

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

ordernumbers put incomparisons by each putin allthe plain tree's
in order10, 20, 30, 40, 50, 60, 700, 1, 2, 2, 3, 3, 31421
back to front70, 60, 50, 40, 30, 20, 100, 1, 2, 2, 3, 3, 31421
a shuffle30, 60, 10, 50, 20, 70, 400, 1, 1, 2, 2, 2, 31111
middle first, level by level40, 20, 60, 10, 30, 50, 700, 1, 1, 2, 2, 2, 21010
Seven numbers four ways, against the plain search tree. In order, the turns save 7 comparisons. The shuffle and middle first never turn, so they cost just what the plain tree does.
numbersorders triedcheapestaveragedearestin order
512067.0788
672089.731111
75,0401012.591414
840,3201315.661817
Every order of 1 to n put in. 1 to 8 numbers make 1 + 2 + 6 + 24 + 120 + 720 + 5,040 + 40,320, which is 46,233 orders. The cheapest is middle first, level by level, each time. At 8, in order is no longer the dearest.
  1. step 33 of 37

    10203040506070

    The way runs out, so hang 10 to the left of 20.

    numbers compared: 3

The thinnest tree of 7 numbers stands on 4 levels, 0 to 3. Middle first puts the same 7 on 3.

where the formula comes from

Each count above, worked out line by line. Each reason names the line it uses, and each 'where does this come from?' box opens a fact from another page.

Why does middle first, level by level, cost (n+1)L−2L+1+2(n + 1)L - 2^{L + 1} + 2 comparisons?
  1. the move: price a number by its level

    the line:
    a number hung on level dcosts d comparisons\begin{gathered} \text{a number hung on level } d \\ \text{costs } d \text{ comparisons} \end{gathered}
    1. step 29 of 35

      123456

      To put 7 in, start at the top.

      numbers compared: 0

    2. step 30 of 35

      123456

      7 is bigger than 4, so go right.

      numbers compared: 1

    3. step 31 of 35

      123456

      7 is bigger than 6, so go right.

      numbers compared: 2

    4. step 32 of 35

      1234567

      The way runs out, so hang 7 to the right of 6.

      numbers compared: 2

    5. step 33 of 35

      1234567

      At 6, the left side is one level high and the right side one level high, so it is balanced.

      numbers compared: 2

    6. step 34 of 35

      1234567

      At 4, the left side is 2 levels high and the right side 2 levels high, so it is balanced.

      numbers compared: 2

    1 to 7, middle first, level by level. 7 meets 4 and 6, 2 comparisons, and hangs on level 2. Climbing back, 6 and 4 are balanced, so nothing turns.

    why it is allowed: The top is level 0. A put meets one number on each level above where it hangs, and none on its own level. The climb back weighs levels, not numbers.

  2. the move: count what a level holds

    the line:
    level d holds at most2d numbers\begin{gathered} \text{level } d \text{ holds at most} \\ 2^d \text{ numbers} \end{gathered}

    why it is allowed: Each place has at most two children. So level 0 holds 1 number, level 1 at most 2, level 2 at most 4, and so on.

  3. the move: see middle first fill the levels

    the line:
    the first number fills level 0,the next 2 level 1, the next 4level 2, and on\begin{gathered} \text{the first number fills level 0,} \\ \text{the next 2 level 1, the next 4} \\ \text{level 2, and on} \end{gathered}
    1 to 8, middle first, a row a level. Each heavy box is a stretch, its middle in blue. At the right, the numbers below each level, line 7's terms.
    levelstretchesnumbers in each
    01 to 88
    11 to 3; 5 to 83; 4
    21; 3; 5; 7 and 81; 1; 1; 2
    381
    Taking a middle out leaves two stretches within one number of each other, so no stretch runs out before its level is full.

    why it is allowed: A stretch is the run of numbers between two already in, or between one and the end of the row. For 1 to 7, 3 is the middle of the stretch between 2 and 4: it meets 4, then 2, and hangs right of 2, on level 2. So each number of level dd is the middle of a stretch whose ends are in, the deeper end one level up, and it hangs below that end. In the drawing, each row is a level.

  4. the move: see nothing turn

    the line:
    so no place’s two sidesare ever two levels apart\begin{gathered} \text{so no place's two sides} \\ \text{are ever two levels apart} \end{gathered}

    why it is allowed: While level dd fills, every level above it is full. So each side of a place higher up reaches the level just above dd, and at most one level more. A place on the level just above dd has at most one level below it. Putting 5 into 4, 2, 6, 1 and 3: 4's left side reaches 2 levels, and its right side goes from 1 to 2. Nothing turns. Lines 3 and 4 hold together, put by put.

  5. the move: find the last level

    the line:
    the last level is L,log⁡2 n rounded down\begin{gathered} \text{the last level is } L, \\ \log_2\, n \text{ rounded down} \end{gathered}

    why it is allowed: Levels 0 to L−1L - 1 hold 2L−12^L - 1 numbers, fewer than nn, as 2L2^L is at most nn. Levels 0 to LL hold one less than 2L+12^{L + 1}, so at least nn, as nn is less than 2L+12^{L + 1}. The page on halving and logarithms shows both, and the box at line 9 the sums. For 7, LL is 2: levels 0 and 1 hold 3, fewer than 7, and levels 0 to 2 hold 7.

  6. the move: count level by level

    the line:
    so each level adds 1 forevery number hung below it\begin{gathered} \text{so each level adds 1 for} \\ \text{every number hung below it} \end{gathered}
    numberits levelmet on level 0met on level 1
    40
    211
    611
    1211
    3211
    5211
    7211
    in all1064
    Each row adds to a number's level; each column counts the numbers below a level. Both ways, 10.

    why it is allowed: By line 1, a number on level 2 is met once on level 0 and once on level 1. So instead of adding each number's level, add, for each level, the numbers below it. In the table, 6 numbers hang below level 0 and 4 below level 1: 10.

  7. the move: count what hangs below

    the line:
    below level d, for d up to L−1,n−(1+2+⋯+2d)numbers\begin{gathered} \text{below level } d, \text{ for } d \text{ up to } L - 1, \\ n - (1 + 2 + \dots + 2^d) \\ \text{numbers} \end{gathered}

    why it is allowed: By lines 3 and 5, levels 0 to dd are full, holding 1+2+⋯+2d1 + 2 + \dots + 2^d numbers by line 2, and every other number hangs below. For 7, 7 less 1, which is 6, below level 0, and 7 less 3, which is 4, below level 1, as in line 6's table.

  8. the move: add the levels

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

    why it is allowed: BB is the comparisons of middle first, level by level. By lines 6 and 7, each level from 0 to L−1L - 1 adds the numbers below it. By line 5, nothing hangs below level LL.

  9. the move: add each doubling

    the line:
    B=(n−1)+(n−3)+(n−7)+⋯+(n−(2L−1))\begin{gathered} B = (n - 1) + (n - 3) + (n - 7) \\ + \dots + \bigl(n - (2^L - 1)\bigr) \end{gathered}
    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 doublings 1, 2, 4 and on add up to one less than the next doubling, as the box under this line shows. So 1 + 2 is 3, and 1 + 2 + 4 is 7. For 7 numbers, LL is 2 and BB is 6 + 4, which is 10.

  10. the move: write each term with n + 1

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

    why it is allowed: Taking away one less than a power of 2 is taking away the power and adding 1, so n−3n - 3 is n+1−4n + 1 - 4. There are LL terms.

  11. the move: gather the n + 1s

    the line:
    B=(n+1)L−(2+4+⋯+2L)B = (n + 1)L - (2 + 4 + \dots + 2^L)

    why it is allowed: The LL terms of line 10 each hold one n+1n + 1.

  12. the move: add the doublings again

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

    why it is allowed: By the box at line 9, the doublings from 1 add up to one less than the next doubling. Here the first 1 is missing, so it is two less. For 7 numbers, 2 + 4 is 6, which is 8 less 2.

  13. the move: open the bracket

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

    why it is allowed: Taking away a bracket takes away each thing in it. For 7 numbers, 8 times 2, less 8, plus 2, is 10, as in line 6's table.

  14. the move: a ceiling

    the line:
    B≤nLB \le nL

    why it is allowed: Each of the LL terms of line 10 is n+1n + 1 less a power of 2, at least 2, so each is less than nn.

  15. the move: a simpler ceiling

    the line:
    B≤n log⁡2 nB \le n \,\log_2\, n

    why it is allowed: LL is at most log⁡2 n\log_2\, n.

  16. the move: read it as a bound

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

    why it is allowed: By line 15, the fixed multiple 1, from 1 number on.

  17. the move: a floor

    the line:
    B≥(L−1)n2+1 for n≥2B \ge (L - 1)\frac{n}{2} + 1 \text{ for } n \ge 2

    why it is allowed: 2L2^L is at most nn, so 2L−12^{L - 1} is at most half of nn. So each term of line 10 but the last is more than half of nn, and the last is at least 1. From 2 numbers on, line 10 has at least one term. For 8, 4 is half.

  18. the move: leave out the 1

    the line:
    B≥(L−1)n2B \ge (L - 1)\frac{n}{2}

    why it is allowed: Taking 1 away from the floor of line 17 leaves a floor.

  19. the move: a floor with logs only

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

    why it is allowed: LL is log⁡2 n\log_2\, n rounded down, so it is more than log⁡2 n\log_2\, n less 1, and L−1L - 1 is more than log⁡2 n−2\log_2\, n - 2.

  20. the move: what 8 numbers allow

    the line:
    log⁡2 n−2≥13 log⁡2 n for n≥8\log_2\, n - 2 \ge \frac{1}{3}\,\log_2\, n \text{ for } n \ge 8

    why it is allowed: From 8 numbers on, log⁡2 n\log_2\, n is at least 3, so 2 is at most two thirds of it, and taking 2 away leaves at least a third. At 8, 3 less 2 is 1, exactly a third of 3.

  21. the move: a simpler floor

    the line:
    B≥n log⁡2 n6 for n≥8B \ge \frac{n \,\log_2\, n}{6} \text{ for } n \ge 8

    why it is allowed: Put line 20 into line 19. A third of log⁡2 n\log_2\, n, times half of nn, is a sixth of n log⁡2 nn \,\log_2\, n.

  22. the move: read it as a bound

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

    why it is allowed: By line 21, the fixed multiple a sixth, from 8 numbers on.

  23. the move: ceiling and floor together

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

    why it is allowed: Lines 16 and 22 bound BB by the same growth, n log⁡2 nn \,\log_2\, n.

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

Why does no order of nn numbers cost more than 2n log⁡2 n2n \,\log_2\, n comparisons?
  1. the move: price a put by the levels

    the line:
    a put meets at most onenumber on each level\begin{gathered} \text{a put meets at most one} \\ \text{number on each level} \end{gathered}
    1. step 29 of 37

      203040506070

      To put 10 in, start at the top.

      numbers compared: 0

    2. step 30 of 37

      203040506070

      10 is smaller than 50, so go left.

      numbers compared: 1

    3. step 31 of 37

      203040506070

      10 is smaller than 30, so go left.

      numbers compared: 2

    4. step 32 of 37

      203040506070

      10 is smaller than 20, so go left.

      numbers compared: 3

    5. step 33 of 37

      10203040506070

      The way runs out, so hang 10 to the left of 20.

      numbers compared: 3

    50, 30, 60, 20, 40 and 70 stand on 3 levels. 10 meets 50, 30 and 20, one a level, 3 comparisons, the most 3 levels allow.

    why it is allowed: Its walk goes down one level at each number it meets, and hangs below the last. So a tree of hh levels costs a put at most hh comparisons.

  2. the move: ask the fewest numbers, not the most levels

    the line:
    N(h), the fewest in h levels, isN(h−1)+N(h−2)+1\begin{gathered} N(h) \text{, the fewest in } h \text{ levels, is} \\ N(h - 1) + N(h - 2) + 1 \end{gathered}
    1. step 33 of 37

      10203040506070

      The way runs out, so hang 10 to the left of 20.

      numbers compared: 3

    2. step 34 of 37

      10203040506070

      At 20, the left side is one level high and the right side empty, so it is balanced.

      numbers compared: 3

    3. step 35 of 37

      10203040506070

      At 30, the left side is 2 levels high and the right side one level high, so it is balanced.

      numbers compared: 3

    4. step 36 of 37

      10203040506070

      At 50, the left side is 3 levels high and the right side 2 levels high, so it is balanced.

      numbers compared: 3

    The thinnest tree of 4 levels holds 7 numbers. Climbing back from 10, at 20, 30 and 50 the left side is one level higher than the right.
    levelsfewest numbersone more2h/22^{h/2}
    1121.41
    2232
    3452.83
    4784
    512135.66
    620218
    Each fewest is the two above it added, plus 1. One more than each stays ahead of the last column, as line 5 shows.

    why it is allowed: The top has one side of h−1h - 1 levels, or the tree would be shorter. The other side is within one level, so at least h−2h - 2. Each side holds fewest when it too is a thinnest tree, and the 1 is the top. So 1, 2, then 2 + 1 + 1, which is 4, then 7, then 12.

  3. the move: add 1 to both

    the line:
    N(h)+1 is (N(h−1)+1)plus (N(h−2)+1)\begin{gathered} N(h) + 1 \text{ is } \bigl(N(h - 1) + 1\bigr) \\ \text{plus } \bigl(N(h - 2) + 1\bigr) \end{gathered}

    why it is allowed: Add 1 to line 2 and share the 2 out, one to each bracket. In the table, 13 is 8 plus 5.

  4. the move: at least double, two levels down

    the line:
    N(h)+1 is at least2(N(h−2)+1)\begin{gathered} N(h) + 1 \text{ is at least} \\ 2\bigl(N(h - 2) + 1\bigr) \end{gathered}

    why it is allowed: By line 2, a thinnest tree of h−1h - 1 levels holds a thinnest tree of h−2h - 2 and more, so line 3's first bracket is at least its second. In the table, 13 is at least twice 5.

  5. the move: climb from the start

    the line:
    N(h)+1 is at least 2h/2\begin{gathered} N(h) + 1 \text{ is at least } 2^{h/2} \end{gathered}

    why it is allowed: It holds at 1 and 2 levels, as the table's first rows show. By line 4, two levels more at least double the left side and exactly double the right. So it holds at every hh: the climb of the page on proof by induction.

  6. the move: turn it round

    the line:
    m numbers stand on atmost 2 log⁡2(m+1) levels\begin{gathered} m \text{ numbers stand on at} \\ \text{most } 2\,\log_2(m + 1) \text{ levels} \end{gathered}

    why it is allowed: A tree of mm numbers on hh levels holds at least N(h)N(h), so m+1m + 1 is at least 2h/22^{h/2} by line 5. So half of hh is at most log⁡2(m+1)\log_2(m + 1), by the page on halving and logarithms, and hh at most twice that. For 12 numbers, at most about 7.4 levels; the table's thinnest has 5.

  7. the move: price put k

    the line:
    put k costs at most2 log⁡2 k comparisons\begin{gathered} \text{put } k \text{ costs at most} \\ 2\,\log_2\, k \text{ comparisons} \end{gathered}

    why it is allowed: Put kk goes into a tree holding one number fewer than kk. So by line 6, with that number as mm, m+1m + 1 is kk, and it has at most 2 log⁡2 k2\,\log_2\, k levels. By line 1, at most that many comparisons. Put 7 goes into 6 numbers: at most about 5.6 levels.

  8. the move: add the puts

    the line:
    U=2 log⁡2 1+2 log⁡2 2+⋯+2 log⁡2 n\begin{gathered} U = 2\,\log_2\, 1 + 2\,\log_2\, 2 \\ + \dots + 2\,\log_2\, n \end{gathered}

    why it is allowed: UU adds line 7's ceiling over the nn puts. Put 1 costs 0, which is 2 log⁡2 12\,\log_2\, 1. For 7, about 24.6.

  9. the move: read it

    the line:
    no order goes past U\begin{gathered} \text{no order goes past } U \end{gathered}
    numbersorders trieddearestceiling UU
    5120813.81
    67201118.98
    75,0401424.60
    840,3201830.60
    Every order of 1 to n tried. The dearest always lies under the ceiling.

    why it is allowed: Lines 1 to 8 hold for every order. The table tries every order of short rows, and the dearest stays well under UU.

  10. the move: a simpler ceiling

    the line:
    U≤2n log⁡2 nU \le 2n\,\log_2\, n

    why it is allowed: Each of the nn terms of line 8 is at most the last, 2 log⁡2 n2\,\log_2\, n.

  11. the move: read it as a bound

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

    why it is allowed: By line 10, UU stays under twice n log⁡2 nn \,\log_2\, n.

try it with a small nn: at n=7n = 7, line 8 gives UU, about 24.6

Why does every order of nn numbers cost at least n log⁡2 n8\frac{n \,\log_2\, n}{8} comparisons, from 4 numbers on?
  1. the move: find the nearest empty spot

    the line:
    in a tree of h levels, everyempty spot is at least half ofh levels below the top\begin{gathered} \text{in a tree of } h \text{ levels, every} \\ \text{empty spot is at least half of} \\ h \text{ levels below the top} \end{gathered}
    1. step 29 of 35

      203040506070

      To put 55 in, start at the top.

      numbers compared: 0

    2. step 30 of 35

      203040506070

      55 is bigger than 50, so go right.

      numbers compared: 1

    3. step 31 of 35

      203040506070

      55 is smaller than 60, so go left.

      numbers compared: 2

    4. step 32 of 35

      20304050556070

      The way runs out, so hang 55 to the left of 60.

      numbers compared: 2

    50, 30, 60, 20, 40 and 70 stand on 3 levels. The nearest empty spot, left of 60, is 2 down, at least half of 3. 55 meets 50 and 60.

    why it is allowed: It holds with no levels, the top itself the empty spot, and with 1 level, every spot 1 down. A taller tree has one side a level shorter than the tree. The rule keeps the other within one level of it, so each side is at most 2 levels shorter. Say 4 levels: each side has at least 2, so a spot is at least 1 down inside its side, 2 from the top, half of 4. Each hh climbs from 2 levels fewer the same way, the climb of the page on proof by induction.

  2. the move: count the levels a tree needs

    the line:
    m numbers need at leastlog⁡2(m+1) levels\begin{gathered} m \text{ numbers need at least} \\ \log_2(m + 1) \text{ levels} \end{gathered}

    why it is allowed: Level 0 holds 1 number, level 1 at most 2, level 2 at most 4, each level at most double the one above. So 3 levels hold at most 7, one less than 8, as the box at line 9 of the question on the cheapest order shows. So hh doublings of 1 reach at least m+1m + 1, and hh is at least log⁡2(m+1)\log_2(m + 1), by the page on halving and logarithms. 7 numbers need 3 levels.

  3. the move: price put k from below

    the line:
    put k costs at least12 log⁡2 k comparisons\begin{gathered} \text{put } k \text{ costs at least} \\ \frac{1}{2}\,\log_2\, k \text{ comparisons} \end{gathered}

    why it is allowed: Put kk goes into a tree holding one number fewer than kk, so of at least log⁡2 k\log_2\, k levels by line 2. By line 1 it hangs at least half that far down, meeting one number a level.

  4. the move: add the puts

    the line:
    F=12(log⁡2 1+log⁡2 2+⋯+log⁡2 n)F = \frac{1}{2}(\log_2\, 1 + \log_2\, 2 + \dots + \log_2\, n)

    why it is allowed: FF adds line 3's floor over the nn puts. For 7, about 6.15.

  5. the move: read it

    the line:
    no order costs less than F\begin{gathered} \text{no order costs less than } F \end{gathered}
    numbersorders triedfloor FFcheapest
    51203.456
    67204.758
    75,0406.1510
    840,3207.6513
    Every order of 1 to n tried. The cheapest always lies above the floor.

    why it is allowed: Lines 1 to 4 hold for every order. The table tries every order of short rows, and the cheapest stays above FF.

  6. the move: write the sum as one log

    the line:
    F=12 log⁡2(1×2×⋯×n)F = \frac{1}{2}\,\log_2(1 \times 2 \times \dots \times n)
    where does this come from?
    question 4 of the page the sorting floorHow does log⁡2 n!\log_2\, n! grow?
    1. the move: name the log

      the line:
      G=log⁡2 n!G = \log_2\, n!

      why it is allowed: Let GG be the log to base 2 of n!n!, for nn from 4 as lines 12 and 15 need. For 8, about 15.30.

    2. the move: factors at most n

      the line:
      n!≤nnn! \le n^n

      why it is allowed: n!n! multiplies nn whole numbers, each at most nn. Putting nn for each gives nnn^n, read nn to the power nn, no smaller. For 8, 40,320 against 16,777,216.

    3. the move: bigger number, bigger log

      the line:
      log⁡2 n!≤log⁡2 nn\log_2\, n! \le \log_2\, n^n

      why it is allowed: On a number line of powers of 2, 16 stands right of 8, and its log, 4, right of 8's log, 3. Any two numbers go the same way, as the page halving and logarithms shows, so line 2 holds for the logs.

    4. the move: into line 1

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

      why it is allowed: By line 3, as GG is the log of n!n!.

    5. the move: log of a power

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

      why it is allowed: For 8: 8 is three 2s, so 8 to the power 8 is 24 2s, since multiplying powers of 2 adds the powers. Each number is 2 raised to its log, so the log of a product adds the logs. nnn^n is a product of nn factors, each nn, so its log is nn times log⁡2 n\log_2\, n.

    6. the move: keep the top half

      the line:
      n!≥the product ofits ⌈n/2⌉ factorsabove half of n\begin{gathered} n! \ge \text{the product of} \\ \text{its } \lceil n/2 \rceil \text{ factors} \\ \text{above half of } n \end{gathered}

      why it is allowed: Drop the factors 1 to half of nn rounded down; each is at least 1, so the product gets no bigger. Half of nn rounded down and rounded up add up to nn, as 3 and 4 for 7. So ⌈n/2⌉\lceil n/2 \rceil are kept, read half of nn rounded up.

    7. the move: half of n for each

      the line:
      n!≥(n2)⌈n/2⌉n! \ge \left(\frac{n}{2}\right)^{\lceil n/2 \rceil}
      for 8multiplied
      8 down to 140,320
      8 × 7 × 6 × 51,680
      4 × 4 × 4 × 4256
      Drop 4 down to 1, then put 4, half of 8, for each factor kept.

      why it is allowed: Each kept factor is above half of nn, so putting half of nn for each gives no bigger product.

    8. the move: bigger number, bigger log

      the line:
      log⁡2 n!≥log⁡2(n2)⌈n/2⌉\log_2\, n! \ge \log_2 \left(\frac{n}{2}\right)^{\lceil n/2 \rceil}

      why it is allowed: As in line 3.

    9. the move: into line 1

      the line:
      G≥log⁡2(n2)⌈n/2⌉G \ge \log_2 \left(\frac{n}{2}\right)^{\lceil n/2 \rceil}

      why it is allowed: By line 8, as GG is the log of n!n!.

    10. the move: log of a power

      the line:
      G≥⌈n2⌉log⁡2 n2G \ge \left\lceil \frac{n}{2} \right\rceil \log_2\, \frac{n}{2}

      why it is allowed: As in line 5. For 8, 4 times 2.

    11. the move: rounding up

      the line:
      ⌈n2⌉≥n2\left\lceil \frac{n}{2} \right\rceil \ge \frac{n}{2}

      why it is allowed: Rounding up makes no smaller, as 3.5 goes up to 4.

    12. the move: log of half of n

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

      why it is allowed: From 4 on, half of nn is at least 2, whose log is 1; by line 3, bigger numbers have bigger logs.

    13. the move: drop the rounding

      the line:
      G≥n2 log⁡2 n2G \ge \frac{n}{2} \,\log_2\, \frac{n}{2}

      why it is allowed: By line 11, half of nn is at most ⌈n/2⌉\lceil n/2 \rceil, as 3.5 against 4 for 7. Each multiplies the log of half of nn, above zero by line 12, so putting half of nn in line 10 makes it no bigger.

    14. the move: halving takes 1 off

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

      why it is allowed: nn is 2 times half of nn, and the log of 2 is 1. So by line 5 the log of half of nn is log⁡2 n−1\log_2\, n - 1. For 8, the log of 4 is 3 less 1.

    15. the move: a fact about n

      the line:
      log⁡2 n2≤log⁡2 n−1\frac{\log_2\, n}{2} \le \log_2\, n - 1

      why it is allowed: From 4 on, log⁡2 n\log_2\, n is at least 2, so half of it is at least 1, and taking 1 away leaves at least half. For 8, 1.5 against 2.

    16. the move: the smaller part

      the line:
      G≥n2×log⁡2 n2G \ge \frac{n}{2} \times \frac{\log_2\, n}{2}

      why it is allowed: By line 15, putting half of log⁡2 n\log_2\, n for log⁡2 n−1\log_2\, n - 1 in line 14 makes it no bigger, as in line 13. For 8, 4 times 1.5, 6.

    17. the move: multiply out

      the line:
      G≥n log⁡2 n4G \ge \frac{n \,\log_2\, n}{4}
      the lognumbers0102030400246810the lognumbers0102030400246810
      • n log⁡2 nn \,\log_2\, n
      • the log of n!n!
      • a quarter of n log⁡2 nn \,\log_2\, n
      The log of n!n! between the other two, from 1 to 10 numbers. At 8: 24, about 15.30, and 6.

      why it is allowed: Half of nn times half of log⁡2 n\log_2\, n.

    18. the move: a ceiling

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

      why it is allowed: G∈O(n log⁡2 n)G \in O(n \,\log_2\, n), read GG is in big O of n log⁡2 nn \,\log_2\, n, says a fixed multiple of it is a ceiling of GG. By line 5, 1 times it, from 4 on.

    19. the move: a floor

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

      why it is allowed: G∈Ω(n log⁡2 n)G \in \Omega(n \,\log_2\, n), read big omega, says a fixed multiple, above zero, is a floor of GG, a floor on growth, not the sorting floor. By line 17, a quarter, from 4 on.

    20. the move: both

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

      why it is allowed: G∈Θ(n log⁡2 n)G \in \Theta(n \,\log_2\, n), read big theta, says both, by lines 18 and 19. GG grows like n log⁡2 nn \,\log_2\, n.

    the whole page: the sorting floor

    why it is allowed: The log of a product adds the logs, as the box under this line uses. The log of 2 times 4, which is 8, is 3, which is 1 + 2.

  7. the move: use how that log grows

    the line:
    F≥n log⁡2 n8 for n≥4F \ge \frac{n \,\log_2\, n}{8} \text{ for } n \ge 4

    why it is allowed: The box at line 6 shows the log is at least a quarter of n log⁡2 nn \,\log_2\, n from 4 on, at its line 17. Half of a quarter is an eighth.

  8. the move: read it as a bound

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

    why it is allowed: By line 7, the fixed multiple an eighth, from 4 on. With the question on the ceiling, every order, the dearest too, costs Θ(n log⁡2 n)\Theta(n \,\log_2\, n).

try it with a small nn: at n=7n = 7, line 4 gives FF, about 6.15

Why does a shuffle cost Θ(n log⁡2 n)\Theta(n \,\log_2\, n) comparisons on average?
  1. the move: a floor from every order

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

    why it is allowed: No order costs less than FF, by lines 5 and 7 of the question on the floor, so neither does their average.

  2. 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 1, the fixed multiple an eighth, from 4 on.

  3. the move: a ceiling from every order

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

    why it is allowed: No order costs more than UU, by lines 9 and 10 of the question on the ceiling, so neither does their average.

  4. 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 3, the fixed multiple 2.

  5. 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 2 and 4 bound AA by the same growth, n log⁡2 nn \,\log_2\, n.

try it on small rows: over every order of 7 numbers, the average AA is about 12.59

count it yourself

Count every comparison as 40, 20, 60, 10, 30, 50 and 70 go into an empty tree, middle first, level by level. Nothing turns.

40, 20, 60, 10, 30, 50, 70, every step written down
stepthe tree, level: numberswhat happensnumbers comparedturns
1Start with an empty tree, and 7 numbers to put in.00
20: 40The tree is empty, so 40 goes at the top.0: 4000
30: 40To put 20 in, start at the top.0: 4000
40: 4020 is smaller than 40, so go left.0: 4010
50: 40; 1: 20The way runs out, so hang 20 to the left of 40.0: 40; 1: 2010
60: 40; 1: 20At 40, the left side is one level high and the right side empty, so it is balanced.0: 40; 1: 2010
70: 40; 1: 20To put 60 in, start at the top.0: 40; 1: 2010
80: 40; 1: 2060 is bigger than 40, so go right.0: 40; 1: 2020
90: 40; 1: 20, 60The way runs out, so hang 60 to the right of 40.0: 40; 1: 20, 6020
100: 40; 1: 20, 60At 40, the left side is one level high and the right side one level high, so it is balanced.0: 40; 1: 20, 6020
110: 40; 1: 20, 60To put 10 in, start at the top.0: 40; 1: 20, 6020
120: 40; 1: 20, 6010 is smaller than 40, so go left.0: 40; 1: 20, 6030
130: 40; 1: 20, 6010 is smaller than 20, so go left.0: 40; 1: 20, 6040
140: 40; 1: 20, 60; 2: 10The way runs out, so hang 10 to the left of 20.0: 40; 1: 20, 60; 2: 1040
150: 40; 1: 20, 60; 2: 10At 20, the left side is one level high and the right side empty, so it is balanced.0: 40; 1: 20, 60; 2: 1040
160: 40; 1: 20, 60; 2: 10At 40, the left side is 2 levels high and the right side one level high, so it is balanced.0: 40; 1: 20, 60; 2: 1040
170: 40; 1: 20, 60; 2: 10To put 30 in, start at the top.0: 40; 1: 20, 60; 2: 1040
180: 40; 1: 20, 60; 2: 1030 is smaller than 40, so go left.0: 40; 1: 20, 60; 2: 1050
190: 40; 1: 20, 60; 2: 1030 is bigger than 20, so go right.0: 40; 1: 20, 60; 2: 1060
200: 40; 1: 20, 60; 2: 10, 30The way runs out, so hang 30 to the right of 20.0: 40; 1: 20, 60; 2: 10, 3060
210: 40; 1: 20, 60; 2: 10, 30At 20, the left side is one level high and the right side one level high, so it is balanced.0: 40; 1: 20, 60; 2: 10, 3060
220: 40; 1: 20, 60; 2: 10, 30At 40, the left side is 2 levels high and the right side one level high, so it is balanced.0: 40; 1: 20, 60; 2: 10, 3060
230: 40; 1: 20, 60; 2: 10, 30To put 50 in, start at the top.0: 40; 1: 20, 60; 2: 10, 3060
240: 40; 1: 20, 60; 2: 10, 3050 is bigger than 40, so go right.0: 40; 1: 20, 60; 2: 10, 3070
250: 40; 1: 20, 60; 2: 10, 3050 is smaller than 60, so go left.0: 40; 1: 20, 60; 2: 10, 3080
260: 40; 1: 20, 60; 2: 10, 30, 50The way runs out, so hang 50 to the left of 60.0: 40; 1: 20, 60; 2: 10, 30, 5080
270: 40; 1: 20, 60; 2: 10, 30, 50At 60, the left side is one level high and the right side empty, so it is balanced.0: 40; 1: 20, 60; 2: 10, 30, 5080
280: 40; 1: 20, 60; 2: 10, 30, 50At 40, the left side is 2 levels high and the right side 2 levels high, so it is balanced.0: 40; 1: 20, 60; 2: 10, 30, 5080
290: 40; 1: 20, 60; 2: 10, 30, 50To put 70 in, start at the top.0: 40; 1: 20, 60; 2: 10, 30, 5080
300: 40; 1: 20, 60; 2: 10, 30, 5070 is bigger than 40, so go right.0: 40; 1: 20, 60; 2: 10, 30, 5090
310: 40; 1: 20, 60; 2: 10, 30, 5070 is bigger than 60, so go right.0: 40; 1: 20, 60; 2: 10, 30, 50100
320: 40; 1: 20, 60; 2: 10, 30, 50, 70The way runs out, so hang 70 to the right of 60.0: 40; 1: 20, 60; 2: 10, 30, 50, 70100
330: 40; 1: 20, 60; 2: 10, 30, 50, 70At 60, the left side is one level high and the right side one level high, so it is balanced.0: 40; 1: 20, 60; 2: 10, 30, 50, 70100
340: 40; 1: 20, 60; 2: 10, 30, 50, 70At 40, the left side is 2 levels high and the right side 2 levels high, so it is balanced.0: 40; 1: 20, 60; 2: 10, 30, 50, 70100
350: 40; 1: 20, 60; 2: 10, 30, 50, 70Done. The tree holds 7 numbers, and it is balanced.0: 40; 1: 20, 60; 2: 10, 30, 50, 70100

In all, 10 numbers compared. The formula from section 4, (n+1)L−2L+1+2(n + 1)L - 2^{L + 1} + 2, gives B=10B = 10 at n=7n = 7: the same.

where you meet it

Two programs keep keys in AVL trees, musl and OpenZFS.

  • musl's tsearch

    musl, a C library, the ready-made code C programs call, builds its tsearch as an AVL tree, each place keeping its levels. So a search, put or take meets at most about twice log⁡2 n\log_2\, n keys, by section 4.

    source: musl's source, src/search/tsearch.c (opens in a new tab)

  • OpenZFS

    OpenZFS, a file system, carries its own general AVL tree, avl.c, which its other parts use to keep things in order in memory.

    source: OpenZFS's source, module/avl/avl.c (opens in a new tab)

1,000 numbers put inthe plain search treean AVL tree
in order499,5008,977
shuffled, the mean of 20about 11,190about 8,723
middle first, level by level7,9877,987
Comparisons to put 1,000 numbers in. Turning saves most on numbers in order; middle first never turns, so both trees cost the same.

what is used instead

Most languages use a red-black tree instead, as Java's TreeMap and C++'s std::map do. Its rule is looser, so its trees may stand taller, but a put turns less on average. Sebastian Bourges' books: 'the stricter the balance rule, the shallower the tree and the more work each update does.' (volume two, chapter 20).

how it compares

Two search trees, each putting nn numbers in, one at a time, counted in comparisons.

wayn shuffled numbers inn numbers in orderextra memoryreach for it when
a plain search treeabout 10,986 at 1,000, its page's worked averagea path: 499,500 at 1,000two links beside each numbernumbers arrive shuffled
an AVL treemeasured, about 8,723 at 1,0008,977 at 1,000two links and its levels beside each numbernumbers may arrive in order
The plain tree's page works out its counts; section 4 bounds the AVL tree's. In order, the turns cut 499,500 to 8,977.

race them on one row of your own