Skip to content

Binary search tree

storing

Level 2 of 3

Also called Sorted binary tree.

how it works

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

A binary search tree keeps numbers in places joined from the top down, each with at most two children. Every number down a place's left side is smaller than it, and every number down its right side bigger. To put a number in, start at the top: smaller goes left, bigger goes right, a level at a time. Where the way runs out, the number hangs. A search walks the same way, stopping at the number. Each number met is one comparison, this page's count. A take lifts the number out. Its one child, if any, takes its place. With two, the smallest number to its right does: one step right, then left until the way runs out, comparing nothing. The run after these pictures puts in 42, 23, 61, 15, 31 and 50, then takes 23 out.

  1. step 13 of 17

    15234261

    To put 31 in, start at the top.

    numbers compared: 0

  2. step 14 of 17

    15234261

    31 is smaller than 42, so go left.

    numbers compared: 1

  3. step 15 of 17

    15234261

    31 is bigger than 23, so go right.

    numbers compared: 2

  4. step 16 of 17

    1523314261

    The way runs out, so hang 31 to the right of 23.

    numbers compared: 2

Operation 5 puts 31 in, after 42, 23, 61 and 15. 31 is smaller than 42, so it goes left. It is bigger than 23, so it goes right, where the way runs out. 2 comparisons; 61 and 15 are never met.
  1. step 24 of 30

    152327314261

    Here is 23.

    numbers compared: 2

  2. step 26 of 30

    152327314261

    Go right once, to 31.

    numbers compared: 2

  3. step 27 of 30

    152327314261

    Go left, to 27.

    numbers compared: 2

  4. step 29 of 30

    1527314261

    27 moves up to where 23 was, and 23 is out.

    numbers compared: 2

After 42, 23, 61, 15, 31 and 27 go in, operation 7 takes 23 out, meeting 42 and 23: 2 comparisons. The walk right to 31, then left to 27, follows links, and the count stays at 2. 23, dashed, is leaving. 27, bigger than 15 and smaller than 31, moves up to where 23 was.
  1. step 20 of 21

    1020304050

    The way runs out, so hang 50 to the right of 40.

    numbers compared: 4

Five numbers in order. Each hangs right of the last, a path 5 levels deep, and 50 meets all 4.
Putting in and taking out: 8 moments of its 28 steps, the steps between them left for the watch page
  1. step 5 of 28

    b23a42

    The way runs out, so hang 23 to the left of 42.

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

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

    watch from here

  2. step 11 of 28

    b23a42c61

    15 is smaller than 23, so go left.

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

    watch from here

  3. step 16 of 28

    d15b23e31a42c61

    The way runs out, so hang 31 to the right of 23.

    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

  4. step 20 of 28

    d15b23e31a42f50c61

    The way runs out, so hang 50 to the left of 61.

    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

  5. step 23 of 28

    d15b23e31a42f50c61

    Here is 23.

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

    watch from here

  6. step 24 of 28

    d15b23e31a42f50c61

    23 has two children, so the smallest number to its right will take its place.

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

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

    watch from here

  7. step 25 of 28

    d15b23e31a42f50c61

    Go right once, to 31.

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

    watch from here

  8. step 27 of 28

    d15e31a42f50c61

    31 moves up to where 23 was, and 23 is out.

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

    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 25
  2. start at the topPython line 27
  3. smaller goes left, bigger goes right, until the number is met or the way runs outPython lines 28, 29, 30 and 31
  4. to put a number in, hang it where the way runs outPython lines 32, 35, 49, 50, 51, 52, 53 and 54
  5. to take a number out, lift it out where it is metPython lines 36, 49, 50, 51, 52, 53 and 54
  6. with one child or none, the child takes its placePython lines 39 and 40
  7. with two, the smallest number to its right takes its placePython lines 41, 42, 43, 44, 45, 46, 47 and 48
  8. a number met when putting, or not met when taking, changes nothingPython lines 33, 34, 37 and 38
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, and a place on each side."""

    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


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 binary_search_tree(operations):
    """Run a list of operations on a binary search tree.

    Each operation is a pair: ('put', n) puts n in, and ('take', n) takes n
    out. Returns the tree as [left, number, right], each side the same
    shape, None where nothing hangs. Each comparison weighs the number at
    one place against n.
    """
    top = None  # an empty tree
    for action, number in operations:
        above, went_left, place = None, False, top  # start at the top
        while place is not None and place.value != number:  # one comparison
            above = place
            went_left = number < place.value  # smaller goes left
            place = place.left if went_left else place.right
        if action == 'put':
            if place is not None:  # already in: nothing changes
                continue
            child = Place(number)  # hang it where the way ran out
        else:
            if place is None:  # not in: nothing changes
                continue
            if place.left is None or place.right is None:  # one child or none
                child = place.left if place.left is not None else place.right
            else:  # two: the smallest number to its right
                parent, child = place, place.right
                while child.left is not None:
                    parent, child = child, child.left
                if parent is not place:
                    parent.left = child.right  # its right side moves up
                    child.right = place.right
                child.left = place.left
        if above is None:  # the child takes the place's spot
            top = child
        elif went_left:
            above.left = child
        else:
            above.right = child
    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. Three orders: in order (1, 2, 3 and on), middle first, 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. Numbers in order climb two steps up for each step across: ten times the numbers, a hundred times the comparisons. Middle first and the shuffles climb a little more than one step: 480 and about 656 comparisons at 100 numbers, 7,987 and about 11,190 at 1,000. 480 to 7,987 is about 17 times. A shuffle costs about 1.4 times middle first. Each shuffle point is the mean of 20 shuffles, a little off section 3's average formula: 648 at 100, 10,986 at 1,000.

numbers compared, ten times more at each mark up

a seconda minutean houra dayslope 2102104106108101010121014101102103104105106107a seconda minutean houra dayslope 210110210310410510610710810910101011101210131014101102103104105106107a seconda minutean houra dayslope 210110210310410510610710810910101011101210131014101102103104105106107

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

  • in order, 1 to nnsolid where measured by running it; dashed where its formula carries it on to ten millionslope 2: ten times n, 100 times the work
  • a shuffle, every order as likelysolid where measured by running it; dashed where its formula carries it on to ten million
  • middle first, then each side the same waysolid where measured by running it; dashed where its formula carries it on to ten million
what numbers in order cost, at a billion comparisons a second
nnnumbers comparedtime
1,000499,500about 500 microseconds
100,0004,999,950,000about 5 seconds
10,000,00049,999,995,000,000about 14 hours

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 a binary search 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
1 to n in order (a path, the dearest), the middle first (the shortest
tree, the cheapest), and the average over 20 shuffles. A comparison weighs
the number at one place against the number put in. The counts are the
same on any computer; only the time differs.
"""
import random
import sys

# shape() calls itself once a level, and 1,000 numbers in order make a
# tree 1,000 levels deep, past Python's usual limit of 1,000 calls.
sys.setrecursionlimit(5000)


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, and a place on each side."""

    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


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 binary_search_tree(operations):
    """Run a list of operations on a binary search tree.

    Each operation is a pair: ('put', n) puts n in, and ('take', n) takes n
    out. Returns the tree as [left, number, right], each side the same
    shape, None where nothing hangs. Each comparison weighs the number at
    one place against n.
    """
    top = None  # an empty tree
    for action, number in operations:
        above, went_left, place = None, False, top  # start at the top
        while place is not None and place.value != number:  # one comparison
            above = place
            went_left = number < place.value  # smaller goes left
            place = place.left if went_left else place.right
        if action == 'put':
            if place is not None:  # already in: nothing changes
                continue
            child = Place(number)  # hang it where the way ran out
        else:
            if place is None:  # not in: nothing changes
                continue
            if place.left is None or place.right is None:  # one child or none
                child = place.left if place.left is not None else place.right
            else:  # two: the smallest number to its right
                parent, child = place, place.right
                while child.left is not None:
                    parent, child = child, child.left
                if parent is not place:
                    parent.left = child.right  # its right side moves up
                    child.right = place.right
                child.left = place.left
        if above is None:  # the child takes the place's spot
            top = child
        elif went_left:
            above.left = child
        else:
            above.right = child
    return shape(top)


def middle_first(low, high):
    """low to high, the middle first, then each side the same way."""
    if low > high:
        return []
    middle = (low + high) // 2
    return [middle] + middle_first(low, middle - 1) + middle_first(middle + 1, high)


def cheapest(n):
    """1 to n put in middle first: every level full but the last."""
    return [('put', number) for number in middle_first(1, n)]


def count(operations):
    """How many comparisons the tree makes on this list of operations."""
    Counted.comparisons = 0
    binary_search_tree([(action, Counted(number)) for action, number in operations])
    return Counted.comparisons


if __name__ == "__main__":
    random.seed(1)
    print(f"{'n':>6} {'in order':>10} {'middle first':>13} {'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([('put', number) for number in row]))
        in_order = [('put', number) for number in range(1, n + 1)]
        print(f"{n:>6} {count(in_order):>10} {count(cheapest(n)):>13} {sum(shuffles) / 20:>10.1f}")

best, worst and average

A put meets one number on each level above where it hangs. So the shape of the tree decides the cost, and the order the numbers arrive in decides the shape.

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, then each side the same wayaveragea shuffle, every order as likelyworstin order, 1 to nn
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. For 100 numbers: 100 lies between 64, 2 to the 6th, and 128, 2 to the 7th, so LL is 6. Then 101 times 6, less 128, plus 2, is 480 for 1002(n+1)H(n)−4n2(n + 1)H(n) - 4n, about 648 for 100n(n−1)2\frac{n(n - 1)}{2}, every pair once
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)Θ(n2)\Theta(n^2)
ceiling, OOO(n log⁡2 n)O(n \,\log_2\, n)O(n log⁡2 n)O(n \,\log_2\, n)O(n2)O(n^2)
floor, Ω\OmegaΩ(n log⁡2 n)\Omega(n \,\log_2\, n)Ω(n log⁡2 n)\Omega(n \,\log_2\, n)Ω(n2)\Omega(n^2)

extra memory: two links 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 all
in order10, 20, 30, 40, 50, 60, 700, 1, 2, 3, 4, 5, 621
back to front70, 60, 50, 40, 30, 20, 100, 1, 2, 3, 4, 5, 621
a shuffle30, 60, 10, 50, 20, 70, 400, 1, 1, 2, 2, 2, 311
middle first40, 20, 60, 10, 30, 50, 700, 1, 1, 2, 2, 2, 210
Seven numbers four ways. In order or back to front, each meets every number before it: a path. Middle first fills the levels, 1, 2 and 4 numbers, so no put meets more than 2.
  1. step 21 of 26

    102030506070

    To put 40 in, start at the top.

    numbers compared: 0

  2. step 22 of 26

    102030506070

    40 is bigger than 30, so go right.

    numbers compared: 1

  3. step 23 of 26

    102030506070

    40 is smaller than 60, so go left.

    numbers compared: 2

  4. step 24 of 26

    102030506070

    40 is smaller than 50, so go left.

    numbers compared: 3

  5. step 25 of 26

    10203040506070

    The way runs out, so hang 40 to the left of 50.

    numbers compared: 3

The grid's shuffle. 40 meets 30, 60 and 50, 3 comparisons, on level 3. These seven stand on levels 0 to 3; in order, 0 to 6.
comparisonsnumbers put in05010015020005101520comparisonsnumbers put in05010015020005101520
  • in order, n(n−1)2\frac{n(n - 1)}{2}
  • a shuffle, on average, 2(n+1)H(n)−4n2(n + 1)H(n) - 4n
  • middle first
Double the numbers, 10 to 20, and in order costs about 4.2 times as much, 45 to 190. Middle first goes from 19 to 54, and a shuffle from about 24 to about 71, each under 3 times.

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 do nn numbers in order cost n(n−1)2\frac{n(n - 1)}{2} comparisons, the most any order can?
  1. the move: price one put

    the line:
    a put compares its number witheach number on its way down\begin{gathered} \text{a put compares its number with} \\ \text{each number on its way down} \end{gathered}
    1. step 15 of 21

      10203040

      To put 50 in, start at the top.

      numbers compared: 0

    2. step 16 of 21

      10203040

      50 is bigger than 10, so go right.

      numbers compared: 1

    3. step 17 of 21

      10203040

      50 is bigger than 20, so go right.

      numbers compared: 2

    4. step 18 of 21

      10203040

      50 is bigger than 30, so go right.

      numbers compared: 3

    5. step 19 of 21

      10203040

      50 is bigger than 40, so go right.

      numbers compared: 4

    6. step 20 of 21

      1020304050

      The way runs out, so hang 50 to the right of 40.

      numbers compared: 4

    50, put in after 10, 20, 30 and 40, is bigger than each and goes right 4 times. 4 comparisons.

    why it is allowed: It starts at the top and meets one number a level until the way runs out. The numbers all differ, so none is its own.

  2. the move: see numbers in order make a path

    the line:
    in order, put k meetsall k−1 numbers before it\begin{gathered} \text{in order, put } k \text{ meets} \\ \text{all } k - 1 \text{ numbers before it} \end{gathered}

    why it is allowed: Each number is bigger than all before it, so it goes right at each, down to the bottom. The tree is one path.

  3. the move: add the puts

    the line:
    W=0+1+2+⋯+(n−1)W = 0 + 1 + 2 + \dots + (n - 1)

    why it is allowed: WW is the comparisons of nn numbers in order. By line 2, put 1 makes 0, put 2 makes 1, and put nn makes n−1n - 1.

  4. the move: use the page on adding up

    the line:
    W=(n−1)((n−1)+1)2W = \frac{(n - 1)\bigl((n - 1) + 1\bigr)}{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 box under this line shows that 1 up to a last number adds to that number times one more, halved. Here the last number is n−1n - 1, and the 0 adds nothing.

  5. the move: tidy

    the line:
    W=n(n−1)2W = \frac{n(n - 1)}{2}

    why it is allowed: (n−1)+1(n - 1) + 1 is nn. For 5 numbers, 5 times 4 over 2 is 10, which is 1 + 2 + 3 + 4.

  6. the move: no order costs more

    the line:
    each pair is comparedat most once, so no ordercosts more than W\begin{gathered} \text{each pair is compared} \\ \text{at most once, so no order} \\ \text{costs more than } W \end{gathered}

    why it is allowed: Two numbers are compared only in the later one's put, when its walk meets the earlier one. So each pair is compared at most once. In order, by line 2, every pair is compared, so WW counts every pair and no order can count more.

  7. the move: a ceiling

    the line:
    W≤n22W \le \frac{n^2}{2}

    why it is allowed: In line 5, n−1n - 1 is less than nn.

  8. the move: read it as a bound

    the line:
    W∈O(n2)W \in O(n^2)

    why it is allowed: By line 7, WW stays under half of n2n^2.

  9. the move: a floor

    the line:
    W≥n24 for n≥2W \ge \frac{n^2}{4} \text{ for } n \ge 2

    why it is allowed: In line 5, n−1n - 1 is at least half of nn once nn is 2 or more.

  10. the move: read it as a bound

    the line:
    W∈Ω(n2)W \in \Omega(n^2)

    why it is allowed: By line 9, from 2 numbers on, WW stays at or above a quarter of n2n^2.

  11. the move: ceiling and floor together

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

    why it is allowed: Lines 8 and 10 bound WW by the same growth, n2n^2.

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

Why can no order cost fewer than (n+1)L−2L+1+2(n + 1)L - 2^{L + 1} + 2 comparisons, and which order costs just that?
  1. the move: price a number by its level

    the line:
    a number hung on level dcost d comparisons\begin{gathered} \text{a number hung on level } d \\ \text{cost } d \text{ comparisons} \end{gathered}
    1. step 21 of 25

      123456

      To put 7 in, start at the top.

      numbers compared: 0

    2. step 22 of 25

      123456

      7 is bigger than 4, so go right.

      numbers compared: 1

    3. step 23 of 25

      123456

      7 is bigger than 6, so go right.

      numbers compared: 2

    4. step 24 of 25

      1234567

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

      numbers compared: 2

    1 to 7, the middle first. Levels 0, 1 and 2 hold 1, 2 and 4 numbers. Putting 7 in meets 4 and 6, 2 comparisons, as 7 hangs on level 2.

    why it is allowed: The top is level 0. A put meets one number on each level above where it hangs, and never its own, as the numbers are all different.

  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: 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.

  4. the move: count what hangs below

    the line:
    below level d, at leastn−(1+2+⋯+2d)numbers\begin{gathered} \text{below level } d, \text{ at least} \\ n - (1 + 2 + \dots + 2^d) \\ \text{numbers} \end{gathered}

    why it is allowed: By line 2, levels 0 to dd hold at most 1+2+⋯+2d1 + 2 + \dots + 2^d numbers between them, and every other number hangs below. For 7, at least 7 less 1, which is 6, below level 0, and 7 less 3, which is 4, below level 1, as in line 3's table.

  5. the move: see middle first fill the levels

    the line:
    middle first, levels 0to L−1 are full\begin{gathered} \text{middle first, levels } 0 \\ \text{to } L - 1 \text{ are full} \end{gathered}
    1 to 8, middle first, a row a level. Each heavy box is a stretch, its upright edges its gaps, its middle in blue. At the right, the numbers below each level, line 7's terms.
    levelstretchesgaps eachmiddle numbers
    01 to 894
    11 to 3; 5 to 84; 52; 6
    21; 3; 5; 7 and 82; 2; 2; 31; 3; 5; 7
    3828
    9 gaps become 4 and 5, then 2, 2, 2 and 3. Down to level 2 each place gets at least 2, so holds a number.

    why it is allowed: Full means a level holds all line 2 allows. Count gaps: nn numbers have n+1n + 1, one before each and one after the last; in the drawing, a stretch's upright edges. The middle number splits them as evenly as can be, and halving rounded down twice is quartering rounded down once, the same rounded up. So each place on level dd gets n+1n + 1 gaps shared by 2d2^d, rounded down or up. Up to level L−1L - 1, 2d2^d is at most half of nn, since 2L2^L is at most nn, as the page on halving and logarithms shows. So the share is more than 2: for 8, level 2 gets 9 shared by 4. Rounded down it is at least 2, and 2 gaps hold a number.

  6. the move: see the rest fill the last level

    the line:
    level L holds the rest,and nothing hangs lower\begin{gathered} \text{level } L \text{ holds the rest,} \\ \text{and nothing hangs lower} \end{gathered}

    why it is allowed: At level LL, n+1n + 1 shared by 2L2^L is at most 2, since nn is less than 2L+12^{L + 1}, by the same page. So each place there holds one number or none, with nothing below it. In line 1's picture, level 2 holds 1, 3, 5 and 7; in line 5's table, level 3 holds 8.

  7. 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 the cheapest order. By lines 3 and 4, no order adds fewer for levels 0 to L−1L - 1. Levels from LL on add at least 0, so leaving them out leaves a floor. By lines 5 and 6, middle first adds just these, and nothing for level LL.

  8. 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.

  9. 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.

  10. 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 9 each hold one n+1n + 1.

  11. 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 8, 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.

  12. 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 3's table.

  13. the move: a ceiling

    the line:
    B≤nLB \le nL

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

  14. 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.

  15. 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 14.

  16. 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 9 but the last is more than half of nn, and the last is at least 1. From 2 numbers on, line 9 has at least one term. For 8, 4 is half.

  17. 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 16 leaves a floor.

  18. 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.

  19. 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.

  20. 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 19 into line 18.

  21. 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 20.

  22. 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 15 and 21 bound BB by the same growth, n log⁡2 nn \,\log_2\, n.

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

Why does a shuffle cost 2(n+1)H(n)−4n2(n + 1)H(n) - 4n comparisons on average?
  1. the move: name the numbers

    the line:
    the numbers are 1,2,…,nin some order\begin{gathered} \text{the numbers are } 1, 2, \dots, n \\ \text{in some order} \end{gathered}

    why it is allowed: Only how the numbers compare matters to the tree, so any nn different numbers act like 1 to nn.

  2. the move: watch two numbers

    the line:
    until one of the numbersfrom i to j is put in,they would all go one way\begin{gathered} \text{until one of the numbers} \\ \text{from } i \text{ to } j \text{ is put in,} \\ \text{they would all go one way} \end{gathered}

    why it is allowed: Take two numbers, ii the smaller and jj the bigger. A number already in the tree that is below ii or above jj sends every number from ii to jj the same way. Watching 2 and 5, a 1 already in sends 2, 3, 4 and 5 all right, and a 6 sends them all left.

  3. the move: a number between parts them

    the line:
    if the first of them put inis between i and j,they are never compared\begin{gathered} \text{if the first of them put in} \\ \text{is between } i \text{ and } j, \\ \text{they are never compared} \end{gathered}
    1. step 18 of 22

      12346

      5 is bigger than 3, so go right.

      numbers compared: 1

    2. step 19 of 22

      12346

      5 is smaller than 6, so go left.

      numbers compared: 2

    3. step 20 of 22

      12346

      5 is bigger than 4, so go right.

      numbers compared: 3

    4. step 21 of 22

      123456

      The way runs out, so hang 5 to the right of 4.

      numbers compared: 3

    3 comes first of 2 to 5, so 2 hangs down its left side. Putting 5 in meets 3, 6 and 4, and never 2.

    why it is allowed: By line 2 it hangs where all of them would go. Then ii goes down its left side and jj down its right, so neither is ever above the other. In the picture, 3 comes first of 2 to 5.

  4. the move: an end meets the other

    the line:
    if it is i or j,they are compared, just once\begin{gathered} \text{if it is } i \text{ or } j, \\ \text{they are compared, just once} \end{gathered}
    1. step 10 of 24

      156

      2 is smaller than 5, so go left.

      numbers compared: 1

    2. step 11 of 24

      156

      2 is bigger than 1, so go right.

      numbers compared: 2

    3. step 12 of 24

      1256

      The way runs out, so hang 2 to the right of 1.

      numbers compared: 2

    3 and 5 traded. Now 5 comes first of 2 to 5, and 2's put meets 5, then 1.

    why it is allowed: By line 2 the other comes later and goes the same way, down to it, so its put compares them. By line 6 of the question on numbers in order, in section 4 of the learn page, no pair is compared twice. In the picture, 5 comes first, and 2's put meets it.

  5. the move: see an end of the pair come first

    the line:
    they are compared in 2 ofevery j−i+1 shuffles\begin{gathered} \text{they are compared in 2 of} \\ \text{every } j - i + 1 \text{ shuffles} \end{gathered}
    orderfirst put1 and 2 meet1 and 3 meet2 and 3 meetcomparisons
    1, 2, 311113
    1, 3, 211113
    2, 1, 321012
    2, 3, 121012
    3, 1, 231113
    3, 2, 131113
    in all64616
    Every order of 1, 2 and 3, each as likely, with a 1 where a pair meets. An order's comparisons are its 1s added up.

    why it is allowed: Trade two of the numbers from ii to jj, as lines 3 and 4 trade 3 and 5. The 1 and the 6 go where they did, and the first of 2 to 5 is now 5. Trading back undoes it, so the orders with 3 first pair off with those with 5 first. A shuffle makes every order as likely, so each of the j−i+1j - i + 1 numbers comes first equally often. By lines 3 and 4, the pair is compared when it is ii or jj. In the table, 1 and 3 meet in 4 of the 6 orders.

  6. the move: count the pairs k apart

    the line:
    n−k pairs stand k apart,each compared in 2k+1of the shuffles\begin{gathered} n - k \text{ pairs stand } k \text{ apart,} \\ \text{each compared in } \frac{2}{k + 1} \\ \text{of the shuffles} \end{gathered}

    why it is allowed: Two numbers stand kk apart when the bigger is the smaller plus kk. Each of 1, 2, and on up to n−kn - k pairs with the number kk above it. With 4 numbers, 3 pairs stand 1 apart. From ii to jj there are then k+1k + 1 numbers, so line 5 gives 2 in k+1k + 1.

  7. the move: average pair by pair

    the line:
    A=(n−1)22+(n−2)23+⋯+1⋅2n\begin{gathered} A = (n - 1)\frac{2}{2} + (n - 2)\frac{2}{3} \\ + \dots + 1 \cdot \frac{2}{n} \end{gathered}

    why it is allowed: AA is the comparisons averaged over every shuffle. A shuffle's comparisons are the pairs that meet in it, each once by line 4. Adding every shuffle's comparisons counts each pair once for each shuffle where it meets. Dividing by the shuffles gives each pair's share, from line 6. In the table: 6 + 4 + 6 is 16 comparisons over 6 orders, or 1, plus 2 thirds, plus 1.

  8. the move: write each term with its bottom

    the line:
    A=(n+1−2)22+(n+1−3)23+⋯+(n+1−n)2n\begin{gathered} A = (n + 1 - 2)\frac{2}{2} + (n + 1 - 3)\frac{2}{3} \\ + \dots + (n + 1 - n)\frac{2}{n} \end{gathered}

    why it is allowed: Each term's bottom is k+1k + 1, from 2 to nn. Its count of pairs, n−kn - k, is n+1n + 1 less that bottom; for the first term, n−1n - 1 is n+1−2n + 1 - 2.

  9. the move: multiply out each term

    the line:
    A=(2(n+1)2−2)+(2(n+1)3−2)+…+(2(n+1)n−2)\begin{gathered} A = \Bigl(\frac{2(n + 1)}{2} - 2\Bigr) \\ + \Bigl(\frac{2(n + 1)}{3} - 2\Bigr) + \dots \\ + \Bigl(\frac{2(n + 1)}{n} - 2\Bigr) \end{gathered}

    why it is allowed: The second term, (n+1−3)23(n + 1 - 3)\frac{2}{3}, is 2(n+1)3−2\frac{2(n + 1)}{3} - 2, since 3 times 2 over 3 is 2. Every term takes away 2 the same way.

  10. the move: gather the terms

    the line:
    A=2(n+1)(12+13+⋯+1n)−2(n−1)\begin{gathered} A = 2(n + 1)\Bigl(\frac{1}{2} + \frac{1}{3} + \dots + \frac{1}{n}\Bigr) \\ - 2(n - 1) \end{gathered}

    why it is allowed: The n−1n - 1 terms of line 9 each take away 2, and each hold 2(n+1)2(n + 1) over their bottom.

  11. the move: name the harmonic sum

    the line:
    A=2(n+1)(H(n)−1)−2(n−1)A = 2(n + 1)\bigl(H(n) - 1\bigr) - 2(n - 1)
    where does this come from?
    question 4 of the page expected costHow does 1+12+13+⋯+1n1 + \frac{1}{2} + \frac{1}{3} + \dots + \frac{1}{n} grow?
    1. the move: name the sum

      the line:
      H=∑k=1n1kH = \sum_{k=1}^{n} \frac{1}{k}

      why it is allowed: Let HH be the harmonic sum to 1 over nn, for nn from 2.

    2. the move: group in blocks

      the line:
      blocks, each starting at1 over a power of 2\begin{gathered} \text{blocks, each starting at} \\ \text{1 over a power of 2} \end{gathered}
      blocktermsadds to01≤ 112≤ 124≤ 135≤ 1
      The sum to 1 over 12, about 3.10, each term a column 1 over k tall. Behind each place of a block stands its first term, dashed, so 4 dashed columns of 1 over 4 make 1. The last block is cut short.

      why it is allowed: Number blocks by jj from 0. Block jj starts at 1 over 2 to the power jj: 1, 1 over 2, 1 over 4, 1 over 8. It stops just before the next start, so it has 2 to the power jj terms: 1 over 4 to 1 over 7 are 4. The last block may be cut short at 1 over nn.

    3. the move: each block at most 1

      the line:
      H≤the number of blocksH \le \text{the number of blocks}

      why it is allowed: Each term of block jj is at most its first, 1 over 2 to the power jj, as a bigger number underneath makes a smaller fraction. So its 2 to the power jj terms, or fewer, add to at most 1. HH is at most 1 per block: 4 for 12.

    4. the move: count the blocks

      the line:
      H≤⌊log⁡2 n⌋+1H \le \lfloor \log_2\, n \rfloor + 1
      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: ⌊log⁡2 n⌋\lfloor \log_2\, n \rfloor is read the log of nn rounded down. By lines 5 and 7 of the page halving and logarithms, 2 to that power is at most nn, and the next power of 2 is above nn. So ⌊log⁡2 n⌋+1\lfloor \log_2\, n \rfloor + 1 blocks start at 1 over 2 to the powers 0 to ⌊log⁡2 n⌋\lfloor \log_2\, n \rfloor. For 12, 3.58 rounds down to 3: the 4 blocks of line 2.

    5. the move: drop the rounding

      the line:
      H≤log⁡2 n+1H \le \log_2\, n + 1

      why it is allowed: Rounding down never adds, so putting log⁡2 n\log_2\, n for ⌊log⁡2 n⌋\lfloor \log_2\, n \rfloor can never lower the right side. For 12, 4 becomes about 4.58.

    6. the move: a fact about n

      the line:
      1≤log⁡2 n1 \le \log_2\, n

      why it is allowed: nn is at least 2, the log of 2 is 1, and a bigger number has a bigger log.

    7. the move: put the log in place of the 1

      the line:
      H≤log⁡2 n+log⁡2 nH \le \log_2\, n + \log_2\, n

      why it is allowed: By line 6 this makes the right side of line 5 no smaller. For 12, 4.58 becomes about 7.17.

    8. the move: add the logs

      the line:
      H≤2 log⁡2 nH \le 2 \,\log_2\, n

      why it is allowed: Two lots of log⁡2 n\log_2\, n.

    9. the move: a ceiling

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

      why it is allowed: By line 8, HH is at most 2 times log⁡2 n\log_2\, n for every nn from 2. H∈O(log⁡2 n)H \in O(\log_2\, n), read HH is in big O of log⁡2 n\log_2\, n, says a fixed multiple of log⁡2 n\log_2\, n is a ceiling of HH: here 2.

    10. the move: blocks after the first term

      the line:
      after the first term,blocks, each ending at1 over a power of 2\begin{gathered} \text{after the first term,} \\ \text{blocks, each ending at} \\ \text{1 over a power of 2} \end{gathered}
      blocktermsadds tofirst11≥ ½22≥ ½34≥ ½left over
      The sum to 1 over 12. Inside each term of a block stands its last term, dashed, so 2 dashed columns of 1 over 4 make one half. 1 over 9 to 1 over 12 are left over.

      why it is allowed: For a floor, group the terms after the first in blocks ending at 1 over 2, 1 over 4, 1 over 8 and on. Each term is then at least its block's last. Whole blocks end at 1 over the powers of 2 from 2 to nn.

    11. the move: drop the leftovers

      the line:
      H is at least 1 plusthe whole blocksadded up\begin{gathered} H \text{ is at least 1 plus} \\ \text{the whole blocks} \\ \text{added up} \end{gathered}

      why it is allowed: Leftover terms are above zero, so leaving them out makes the total no bigger.

    12. the move: whole blocks at least one half

      the line:
      H≥1+12×the numberof whole blocks\begin{gathered} H \ge 1 + \frac{1}{2} \times \text{the number} \\ \text{of whole blocks} \end{gathered}

      why it is allowed: Number the whole blocks by ii from 1. Block ii runs from just after 1 over half of 2 to the power ii to 1 over 2 to the power ii. That is half that many terms, each at least its last, so at least one half. For 12, 1 over 3 + 1 over 4 is at least 2 times 1 over 4. With line 11, HH is at least 1 plus one half per whole block: 2.5.

    13. the move: count the whole blocks

      the line:
      H≥1+⌊log⁡2 n⌋2H \ge 1 + \frac{\lfloor \log_2\, n \rfloor}{2}
      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: As in line 4, whole blocks end at 1 over 2 to the powers 1 to ⌊log⁡2 n⌋\lfloor \log_2\, n \rfloor, that many blocks. For 12, 3.

    14. the move: rounding takes off less than 1

      the line:
      H≥1+log⁡2 n−12H \ge 1 + \frac{\log_2\, n - 1}{2}

      why it is allowed: Rounding down takes off less than 1, so putting log⁡2 n\log_2\, n less 1 for ⌊log⁡2 n⌋\lfloor \log_2\, n \rfloor can only lower the right side. For 12, 2.5 becomes about 2.29.

    15. the move: halve each part

      the line:
      H≥1+log⁡2 n2−12H \ge 1 + \frac{\log_2\, n}{2} - \frac{1}{2}

      why it is allowed: Half of (log⁡2 n\log_2\, n less 1) is half of log⁡2 n\log_2\, n, less one half.

    16. the move: change the order

      the line:
      H≥1−12+log⁡2 n2H \ge 1 - \frac{1}{2} + \frac{\log_2\, n}{2}

      why it is allowed: Adding and taking away go in any order.

    17. the move: 1 less one half

      the line:
      H≥12+log⁡2 n2H \ge \frac{1}{2} + \frac{\log_2\, n}{2}

      why it is allowed: 1 less one half is one half.

    18. the move: drop the one half

      the line:
      H≥log⁡2 n2H \ge \frac{\log_2\, n}{2}

      why it is allowed: Taking away one half makes the right side smaller. For 12, about 1.79.

    19. the move: a floor

      the line:
      H∈Ω(log⁡2 n)H \in \Omega(\log_2\, n)
      the sumterms024681005101520the sumterms024681005101520
      • the ceiling, 2 log⁡2 n2 \,\log_2\, n
      • the harmonic sum
      • the floor, log⁡2 n2\frac{\log_2\, n}{2}
      From 2 terms on, the harmonic sum lies between its ceiling and floor. At 16: 8, about 3.38, and 2.

      why it is allowed: By line 18, HH is at least one half times log⁡2 n\log_2\, n for every nn from 2. H∈Ω(log⁡2 n)H \in \Omega(\log_2\, n), read HH is in big omega of log⁡2 n\log_2\, n, says a fixed multiple of log⁡2 n\log_2\, n, above zero, is a floor of HH.

    20. the move: ceiling and floor together

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

      why it is allowed: H∈Θ(log⁡2 n)H \in \Theta(\log_2\, n), read HH is in big theta of log⁡2 n\log_2\, n, says both: by lines 9 and 19, for every nn from 2, HH lies between one half and 2 times log⁡2 n\log_2\, n. It grows like log⁡2 n\log_2\, n.

    the whole page: expected cost

    why it is allowed: The bracket of line 10 is H(n)H(n) without its first 1. The box under this line shows how H(n)H(n) grows.

  12. the move: open the first bracket

    the line:
    A=2(n+1)H(n)−2(n+1)−2(n−1)\begin{gathered} A = 2(n + 1)H(n) \\ - 2(n + 1) - 2(n - 1) \end{gathered}

    why it is allowed: Taking 1 away inside the bracket takes away 2(n+1)2(n + 1).

  13. the move: gather

    the line:
    A=2(n+1)H(n)−4nA = 2(n + 1)H(n) - 4n

    why it is allowed: 2(n+1)2(n + 1) and 2(n−1)2(n - 1) add up to 4n4n, the 2 and the take-away 2 cancelling. For 3 numbers, 2 times 4 times 11 sixths, less 12, is 16 over 6, the table's average.

  14. the move: how big the harmonic sum gets

    the line:
    H(n)≤log⁡2 n+1 for n≥2H(n) \le \log_2\, n + 1 \text{ for } n \ge 2

    why it is allowed: The box at line 11 shows this, in its line 5.

  15. the move: a ceiling

    the line:
    A≤2(n+1)(log⁡2 n+1)−4nA \le 2(n + 1)(\log_2\, n + 1) - 4n

    why it is allowed: Put line 14 into line 13.

  16. the move: open the bracket

    the line:
    A≤2(n+1) log⁡2 n+2(n+1)−4nA \le 2(n + 1)\,\log_2\, n + 2(n + 1) - 4n

    why it is allowed: Multiply 2(n+1)2(n + 1) by each of log⁡2 n\log_2\, n and 1.

  17. the move: gather

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

    why it is allowed: 2(n+1)2(n + 1) less 4n4n leaves −2n+2- 2n + 2.

  18. the move: drop what is not positive

    the line:
    A≤2(n+1) log⁡2 nA \le 2(n + 1)\,\log_2\, n

    why it is allowed: From 1 number on, −2n+2- 2n + 2 is at most 0.

  19. the move: a simpler ceiling

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

    why it is allowed: n+1n + 1 is at most 2n2n, and log⁡2 n\log_2\, n is not negative.

  20. 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 19.

  21. the move: a floor from the cheapest order

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

    why it is allowed: No shuffle costs less than the cheapest order, so neither does their average. The cheapest order costs at least this, by line 20 of the question on the cheapest order, in section 4 of the learn page.

  22. 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 21.

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

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

count it yourself

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

40, 20, 60, 10, 30, 50, 70, every step written down
stepthe tree, level: numberswhat happensnumbers compared
1Start with an empty tree, and 7 operations to do.0
20: 40The tree is empty, so 40 goes at the top.0: 400
30: 40To put 20 in, start at the top.0: 400
40: 4020 is smaller than 40, so go left.0: 401
50: 40; 1: 20The way runs out, so hang 20 to the left of 40.0: 40; 1: 201
60: 40; 1: 20To put 60 in, start at the top.0: 40; 1: 201
70: 40; 1: 2060 is bigger than 40, so go right.0: 40; 1: 202
80: 40; 1: 20, 60The way runs out, so hang 60 to the right of 40.0: 40; 1: 20, 602
90: 40; 1: 20, 60To put 10 in, start at the top.0: 40; 1: 20, 602
100: 40; 1: 20, 6010 is smaller than 40, so go left.0: 40; 1: 20, 603
110: 40; 1: 20, 6010 is smaller than 20, so go left.0: 40; 1: 20, 604
120: 40; 1: 20, 60; 2: 10The way runs out, so hang 10 to the left of 20.0: 40; 1: 20, 60; 2: 104
130: 40; 1: 20, 60; 2: 10To put 30 in, start at the top.0: 40; 1: 20, 60; 2: 104
140: 40; 1: 20, 60; 2: 1030 is smaller than 40, so go left.0: 40; 1: 20, 60; 2: 105
150: 40; 1: 20, 60; 2: 1030 is bigger than 20, so go right.0: 40; 1: 20, 60; 2: 106
160: 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, 306
170: 40; 1: 20, 60; 2: 10, 30To put 50 in, start at the top.0: 40; 1: 20, 60; 2: 10, 306
180: 40; 1: 20, 60; 2: 10, 3050 is bigger than 40, so go right.0: 40; 1: 20, 60; 2: 10, 307
190: 40; 1: 20, 60; 2: 10, 3050 is smaller than 60, so go left.0: 40; 1: 20, 60; 2: 10, 308
200: 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, 508
210: 40; 1: 20, 60; 2: 10, 30, 50To put 70 in, start at the top.0: 40; 1: 20, 60; 2: 10, 30, 508
220: 40; 1: 20, 60; 2: 10, 30, 5070 is bigger than 40, so go right.0: 40; 1: 20, 60; 2: 10, 30, 509
230: 40; 1: 20, 60; 2: 10, 30, 5070 is bigger than 60, so go right.0: 40; 1: 20, 60; 2: 10, 30, 5010
240: 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, 7010
250: 40; 1: 20, 60; 2: 10, 30, 50, 70Done. The tree holds 7 numbers.0: 40; 1: 20, 60; 2: 10, 30, 50, 7010

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

Java's TreeMap and GCC's std::map for C++, two programming languages, keep keys in balanced search trees.

  • Java's TreeMap

    Java's TreeMap keeps its keys in a red-black tree, a binary search tree that mends its shape after each put or take, so it stays balanced. One search, put or take then takes time growing no faster than log⁡2 n\log_2\, n, in any order; nn puts cost nn times that.

    source: Java's documentation, java.util.TreeMap (opens in a new tab)

  • C++'s std::map

    C++'s map keeps its keys in order, and the standard asks that finding one take time that grows no faster than log⁡2 n\log_2\, n. GCC's C++ library, libstdc++, builds it as a red-black tree.

    source: the C++ standard, associative.reqmts (opens in a new tab), the ordered containers' requirements; GCC's libstdc++, bits/stl_tree.h

questionhow TreeMap asks ita hash table
the smallest keyfirstKey()reads every slot
the next key after 42higherKey(42)reads every slot
every key from 20 to 50, in ordersubMap(20, true, 50, true)reads every slot, then sorts
TreeMap finds the smallest by going left to the end, and the next after 42 by a search's walk down. It lists the third by finding 20, then stepping on to each key up to 50. In subMap, true says 20 and 50 count.

what is used instead

A plain search tree is rarely used as it is. Libraries, the ready-made code a language comes with, keep theirs balanced, so numbers in order cannot make a path. Sebastian Bourges' books are blunt: 'Do not reach for a plain binary search tree at all' (volume two, chapter 19). When the only question is whether a number is in, a hash table answers with fewer comparisons on average. Its slots must stay mostly empty, as this site's hash table pages show.

how it compares

Two ways to keep numbers in order, each putting nn numbers in, one at a time. A chain's look, like a comparison here, weighs one number against the one in hand.

wayn shuffled numbers in, on averagen numbers in orderextra memoryreach for it when
a search tree2(n+1)H(n)−4n2(n + 1)H(n) - 4n comparisons, about 10,986 at 1,000n(n−1)2\frac{n(n - 1)}{2} comparisons, a pathtwo links beside each numbernumbers arrive shuffled, or the tree is kept balanced
a chain kept in orderabout a quarter of nn times nn looks, about 250,743 at 1,000every number already in, each put: 499,500 looks at 1,000one link beside each numberyou cut or join whole runs of numbers at once
Section 4 works out the tree's counts, and the linked list's page the chain's. Shuffled, the tree is far cheaper; in order, both meet every number already in.
comparisons or looks, on averageshuffled numbers put in0100200300400500010203040comparisons or looks, on averageshuffled numbers put in0100200300400500010203040
  • a chain kept in order, from the linked list's page
  • a search tree, 2(n+1)H(n)−4n2(n + 1)H(n) - 4n
At 40 shuffled numbers, about 426 looks in the chain against 191 comparisons in the tree.

race them on one row of your own