Binary search 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.
step 13 of 17
To put 31 in, start at the top.
numbers compared: 0
step 14 of 17
31 is smaller than 42, so go left.
numbers compared: 1
step 15 of 17
31 is bigger than 23, so go right.
numbers compared: 2
step 16 of 17
The way runs out, so hang 31 to the right of 23.
numbers compared: 2
step 24 of 30
Here is 23.
numbers compared: 2
step 26 of 30
Go right once, to 31.
numbers compared: 2
step 27 of 30
Go left, to 27.
numbers compared: 2
step 29 of 30
27 moves up to where 23 was, and 23 is out.
numbers compared: 2
step 20 of 21
The way runs out, so hang 50 to the right of 40.
numbers compared: 4
step 5 of 28
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.
step 11 of 28
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
step 16 of 28
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.
step 20 of 28
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.
step 23 of 28
Here is 23.
what it remembers to know where it is
- doing operation
- 7
- looking at
- 23
- in the tree
- 6
step 24 of 28
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.
step 25 of 28
Go right once, to 31.
what it remembers to know where it is
- doing operation
- 7
- looking at
- 31
- in the tree
- 5
step 27 of 28
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.
the steps, in plain words
choose a step to mark the Python, a programming language, that does it
- start with an empty treePython line 25
- start at the topPython line 27
- smaller goes left, bigger goes right, until the number is met or the way runs outPython lines 28, 29, 30 and 31
- to put a number in, hang it where the way runs outPython lines 32, 35, 49, 50, 51, 52, 53 and 54
- to take a number out, lift it out where it is metPython lines 36, 49, 50, 51, 52, 53 and 54
- with one child or none, the child takes its placePython lines 39 and 40
- with two, the smallest number to its right takes its placePython lines 41, 42, 43, 44, 45, 46, 47 and 48
- 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
, how many numbers are in the tree, ten times more at each mark to the right
- in order, 1 to solid 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
| numbers compared | time | |
|---|---|---|
| 1,000 | 499,500 | about 500 microseconds |
| 100,000 | 4,999,950,000 | about 5 seconds |
| 10,000,000 | 49,999,995,000,000 | about 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.
| bestmiddle first, then each side the same way | averagea shuffle, every order as likely | worstin order, 1 to | |
|---|---|---|---|
| numbers compared | , with the rounded down. For 100 numbers: 100 lies between 64, 2 to the 6th, and 128, 2 to the 7th, so is 6. Then 101 times 6, less 128, plus 2, is 480 for 100 | , about 648 for 100 | , every pair once |
| how the numbers compared grow in each case | |||
| tight, | |||
| ceiling, | |||
| floor, | |||
extra memory: two links beside each number
Extra memory is the room it needs on top of the input itself, while it runs.
| order | numbers put in | comparisons by each put | in all |
|---|---|---|---|
| in order | 10, 20, 30, 40, 50, 60, 70 | 0, 1, 2, 3, 4, 5, 6 | 21 |
| back to front | 70, 60, 50, 40, 30, 20, 10 | 0, 1, 2, 3, 4, 5, 6 | 21 |
| a shuffle | 30, 60, 10, 50, 20, 70, 40 | 0, 1, 1, 2, 2, 2, 3 | 11 |
| middle first | 40, 20, 60, 10, 30, 50, 70 | 0, 1, 1, 2, 2, 2, 2 | 10 |
step 21 of 26
To put 40 in, start at the top.
numbers compared: 0
step 22 of 26
40 is bigger than 30, so go right.
numbers compared: 1
step 23 of 26
40 is smaller than 60, so go left.
numbers compared: 2
step 24 of 26
40 is smaller than 50, so go left.
numbers compared: 3
step 25 of 26
The way runs out, so hang 40 to the left of 50.
numbers compared: 3
- in order,
- a shuffle, on average,
- middle first
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.
the move: price one put
the line:step 15 of 21
To put 50 in, start at the top.
numbers compared: 0
step 16 of 21
50 is bigger than 10, so go right.
numbers compared: 1
step 17 of 21
50 is bigger than 20, so go right.
numbers compared: 2
step 18 of 21
50 is bigger than 30, so go right.
numbers compared: 3
step 19 of 21
50 is bigger than 40, so go right.
numbers compared: 4
step 20 of 21
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.
the move: see numbers in order make a path
the line: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.
guess it, thenthe move: add the puts
the line:why it is allowed: is the comparisons of numbers in order. By line 2, put 1 makes 0, put 2 makes 1, and put makes .
guess it, thenthe move: use the page on adding up
the line:where does this come from?
question 1 of the page adding up Fit two staircases of squares together. What shape do they make? the move: draw the sum as a staircase
the line:why it is allowed: Let be the sum of the whole numbers from 1 to . Draw it as a staircase, a column for each number: 1 square, then 2, and so on up to . For 5, columns of 1, 2, 3, 4 and 5 hold 15 squares.
the move: take two staircases
the line:why it is allowed: Two staircases hold twice the squares. Doubling both sides of line 1 keeps it true.
the move: fit them into a rectangle
the line: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 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 , and the columns fill a rectangle wide and tall.
the move: halve both sides
the line:why it is allowed: Halving both sides of line 3 keeps it true and leaves one . For 5, half of 30 is 15.
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 , and the 0 adds nothing.
guess it, thenthe move: tidy
the line:why it is allowed: is . For 5 numbers, 5 times 4 over 2 is 10, which is 1 + 2 + 3 + 4.
guess it, thenthe move: no order costs more
the line: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 counts every pair and no order can count more.
guess it, thenthe move: a ceiling
the line:why it is allowed: In line 5, is less than .
guess it, thenthe move: read it as a bound
the line:why it is allowed: By line 7, stays under half of .
guess it, thenthe move: a floor
the line:why it is allowed: In line 5, is at least half of once is 2 or more.
guess it, thenthe move: read it as a bound
the line:why it is allowed: By line 9, from 2 numbers on, stays at or above a quarter of .
guess it, thenthe move: ceiling and floor together
the line:why it is allowed: Lines 8 and 10 bound by the same growth, .
guess it, then
try it with a small : at , line 3 gives , which you can work out by hand
the move: price a number by its level
the line:step 21 of 25
To put 7 in, start at the top.
numbers compared: 0
step 22 of 25
7 is bigger than 4, so go right.
numbers compared: 1
step 23 of 25
7 is bigger than 6, so go right.
numbers compared: 2
step 24 of 25
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.
the move: count what a level holds
the line: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.
guess it, thenthe move: count level by level
the line:number its level met on level 0 met on level 1 4 0 2 1 1 6 1 1 1 2 1 1 3 2 1 1 5 2 1 1 7 2 1 1 in all 10 6 4 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.
guess it, thenthe move: count what hangs below
the line:why it is allowed: By line 2, levels 0 to hold at most 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.
guess it, thenthe move: see middle first fill the levels
the line: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. level stretches gaps each middle numbers 0 1 to 8 9 4 1 1 to 3; 5 to 8 4; 5 2; 6 2 1; 3; 5; 7 and 8 2; 2; 2; 3 1; 3; 5; 7 3 8 2 8 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: numbers have , 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 gets gaps shared by , rounded down or up. Up to level , is at most half of , since is at most , 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.
guess it, thenthe move: see the rest fill the last level
the line:why it is allowed: At level , shared by is at most 2, since is less than , 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.
guess it, thenthe move: add the levels
the line:why it is allowed: is the comparisons of the cheapest order. By lines 3 and 4, no order adds fewer for levels 0 to . Levels from 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 .
guess it, thenthe move: add each doubling
the line:where does this come from?
question 1 of the page doubling and halving sumsAdd . What is the total? the move: name the sum
the line:why it is allowed: Let be the doubling sum up to . For as 3, it is 1 + 2 + 4 + 8.
the move: double both sides
the line:why it is allowed: Each term doubled is the next one along, and becomes . Doubling both sides keeps them equal. The plan: the two sums share all but their ends.
the move: take line 1 away
the line:why it is allowed: Take from both sides of line 2. On the right, write out as line 1 does.
the move: tidy the left side
the line:why it is allowed: Two lots of less one lot is one lot.
the move: cancel what both brackets share
the line:when n is 3 1 2 4 8 16 first bracket 2 4 8 16 second bracket 1 2 4 8 left over take away 1 16 Line 4 when is 3. The 2, 4 and 8 cancel, leaving 16 less 1, which is 15. why it is allowed: Every term from 2 to is in both brackets and cancels, leaving less 1.
the move: the terms before the last
the line:why it is allowed: The sum of line 5 stopping one term sooner: line 5 with for . For 3, it is 1 + 2 + 4. At as 0 no terms are left, adding to 0, and 2 to the power 0, less 1, is 0 too.
the move: tidy the power
the line:why it is allowed: One more than is . For 3, 1 + 2 + 4 is 7, one less than 8.
the move: read it
the line: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 , twice the last.
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, is 2 and is 6 + 4, which is 10.
guess it, thenthe move: write each term with n + 1
the line:why it is allowed: Taking away one less than a power of 2 is taking away the power and adding 1, so is . There are terms.
guess it, thenthe move: gather the n + 1s
the line:why it is allowed: The terms of line 9 each hold one .
guess it, thenthe move: add the doublings again
the line: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.
guess it, thenthe move: open the bracket
the line: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.
guess it, thenthe move: a ceiling
the line:why it is allowed: Each of the terms of line 9 is less a power of 2, at least 2, so each is less than .
guess it, thenthe move: a simpler ceiling
the line:why it is allowed: is at most .
guess it, thenthe move: read it as a bound
the line:why it is allowed: By line 14.
guess it, thenthe move: a floor
the line:why it is allowed: is at most , so is at most half of . So each term of line 9 but the last is more than half of , and the last is at least 1. From 2 numbers on, line 9 has at least one term. For 8, 4 is half.
guess it, thenthe move: leave out the 1
the line:why it is allowed: Taking 1 away from the floor of line 16 leaves a floor.
guess it, thenthe move: a floor with logs only
the line:why it is allowed: is rounded down, so it is more than less 1, and is more than .
guess it, thenthe move: what 8 numbers allow
the line:why it is allowed: From 8 numbers on, 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.
guess it, thenthe move: a simpler floor
the line:why it is allowed: Put line 19 into line 18.
guess it, thenthe move: read it as a bound
the line:why it is allowed: By line 20.
guess it, thenthe move: ceiling and floor together
the line:why it is allowed: Lines 15 and 21 bound by the same growth, .
guess it, then
try it with a small : at , line 7 gives , which you can work out by hand
the move: name the numbers
the line:why it is allowed: Only how the numbers compare matters to the tree, so any different numbers act like 1 to .
the move: watch two numbers
the line:why it is allowed: Take two numbers, the smaller and the bigger. A number already in the tree that is below or above sends every number from to 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.
guess it, thenthe move: a number between parts them
the line:step 18 of 22
5 is bigger than 3, so go right.
numbers compared: 1
step 19 of 22
5 is smaller than 6, so go left.
numbers compared: 2
step 20 of 22
5 is bigger than 4, so go right.
numbers compared: 3
step 21 of 22
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 goes down its left side and down its right, so neither is ever above the other. In the picture, 3 comes first of 2 to 5.
guess it, thenthe move: an end meets the other
the line:step 10 of 24
2 is smaller than 5, so go left.
numbers compared: 1
step 11 of 24
2 is bigger than 1, so go right.
numbers compared: 2
step 12 of 24
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.
guess it, thenthe move: see an end of the pair come first
the line:order first put 1 and 2 meet 1 and 3 meet 2 and 3 meet comparisons 1, 2, 3 1 1 1 1 3 1, 3, 2 1 1 1 1 3 2, 1, 3 2 1 0 1 2 2, 3, 1 2 1 0 1 2 3, 1, 2 3 1 1 1 3 3, 2, 1 3 1 1 1 3 in all 6 4 6 16 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 to , 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 numbers comes first equally often. By lines 3 and 4, the pair is compared when it is or . In the table, 1 and 3 meet in 4 of the 6 orders.
guess it, thenthe move: count the pairs k apart
the line:why it is allowed: Two numbers stand apart when the bigger is the smaller plus . Each of 1, 2, and on up to pairs with the number above it. With 4 numbers, 3 pairs stand 1 apart. From to there are then numbers, so line 5 gives 2 in .
guess it, thenthe move: average pair by pair
the line:why it is allowed: 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.
guess it, thenthe move: write each term with its bottom
the line:why it is allowed: Each term's bottom is , from 2 to . Its count of pairs, , is less that bottom; for the first term, is .
guess it, thenthe move: multiply out each term
the line:why it is allowed: The second term, , is , since 3 times 2 over 3 is 2. Every term takes away 2 the same way.
guess it, thenthe move: gather the terms
the line:why it is allowed: The terms of line 9 each take away 2, and each hold over their bottom.
guess it, thenthe move: name the harmonic sum
the line:where does this come from?
question 4 of the page expected costHow does grow? the move: name the sum
the line:why it is allowed: Let be the harmonic sum to 1 over , for from 2.
the move: group in blocks
the line: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 from 0. Block starts at 1 over 2 to the power : 1, 1 over 2, 1 over 4, 1 over 8. It stops just before the next start, so it has 2 to the power terms: 1 over 4 to 1 over 7 are 4. The last block may be cut short at 1 over .
the move: each block at most 1
the line:why it is allowed: Each term of block is at most its first, 1 over 2 to the power , as a bigger number underneath makes a smaller fraction. So its 2 to the power terms, or fewer, add to at most 1. is at most 1 per block: 4 for 12.
the move: count the blocks
the line:where does this come from?
question 2 of the page halving and logarithmsHalve , rounding down each time. How many halvings reach 1? the move: name the log rounded down
the line:Rounding down, 11 halves to 5, 2 and 1. In blue, each log rounded down: 3, 2, 1, 0, one less at each halving. why it is allowed: Here is the number halved, from 2 up; for 11, is 3.
the move: rounding down never adds
the line:why it is allowed: For 11, 3 is at most 3.46.
the move: rounding down takes off less than 1
the line:why it is allowed: For 11, 4 is above 3.46.
the move: raise 2 to each side of line 2
the line:why it is allowed: 2 raised to a bigger power gives a bigger number. For 11, 8 is at most about 11.
the move: 2 to the log of n is n
the line:why it is allowed: By what a log is. For 11, 8 is at most 11.
the move: raise 2 to each side of line 3
the line:why it is allowed: As in line 4. For 11, about 11 is below 16.
the move: 2 to the log of n is n
the line:why it is allowed: As in line 5. For 11, 11 is below 16.
the move: halve both sides of line 5
the line:why it is allowed: For 11, 4 is at most 5.5, which is not whole.
the move: write the half as a power
the line:why it is allowed: Half a power of 2 has one 2 fewer. Half of 8 is 4.
the move: round the half down
the line:why it is allowed: is the half rounded down, 5 for 11. A whole number at most 5.5 is at most 5. The left side, 4 for 11, is whole, as is at least 1 for from 2 up.
the move: halve both sides of line 7
the line:why it is allowed: For 11, 5.5 is below 8.
the move: write the half as a power
the line:why it is allowed: As in line 9. Half of 16 is 8.
the move: round the half down
the line:why it is allowed: Rounding down never adds. For 11, 5 is below 8.
the move: take the log of line 10
the line:why it is allowed: A bigger number has a bigger log. For 11, the log of 4 is at most the log of 5.
the move: the log of a power of 2 is the power
the line:why it is allowed: For 11, the log of 4 is 2, at most about 2.32.
the move: take the log of line 13
the line:why it is allowed: As in line 14. For 11, the log of 5 is below the log of 8.
the move: the log of a power of 2 is the power
the line:why it is allowed: For 11, about 2.32 is below 3.
the move: round the log down
the line:the number at least below its log rounded down 11 8 16 3 5 4 8 2 2 2 4 1 1 1 2 0 Each halving takes 1 off the log rounded down. why it is allowed: By lines 15 and 17, the log of the half is at least one less than and below , so it rounds down to one less. For 11, about 2.32 rounds down to 2.
the move: use line 18 again and again
the line:why it is allowed: While the log rounded down is 1 or more, the number is at least 2 to the power 1, which is 2. So line 18 takes 1 off each halving, down to 0 after . For 11, 3, 2, 1, 0.
the move: a log rounded down to 0 belongs to 1
the line:why it is allowed: Such a log is at least 0 and below 1, so its number is at least 1 and below 2. It is 1.
why it is allowed: is read the log of rounded down. By lines 5 and 7 of the page halving and logarithms, 2 to that power is at most , and the next power of 2 is above . So blocks start at 1 over 2 to the powers 0 to . For 12, 3.58 rounds down to 3: the 4 blocks of line 2.
the move: drop the rounding
the line:why it is allowed: Rounding down never adds, so putting for can never lower the right side. For 12, 4 becomes about 4.58.
the move: a fact about n
the line:why it is allowed: is at least 2, the log of 2 is 1, and a bigger number has a bigger log.
the move: put the log in place of the 1
the line: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.
the move: add the logs
the line:why it is allowed: Two lots of .
the move: a ceiling
the line:why it is allowed: By line 8, is at most 2 times for every from 2. , read is in big O of , says a fixed multiple of is a ceiling of : here 2.
the move: blocks after the first term
the line: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 .
the move: drop the leftovers
the line:why it is allowed: Leftover terms are above zero, so leaving them out makes the total no bigger.
the move: whole blocks at least one half
the line:why it is allowed: Number the whole blocks by from 1. Block runs from just after 1 over half of 2 to the power to 1 over 2 to the power . 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, is at least 1 plus one half per whole block: 2.5.
the move: count the whole blocks
the line:where does this come from?
question 2 of the page halving and logarithmsHalve , rounding down each time. How many halvings reach 1? the move: name the log rounded down
the line:Rounding down, 11 halves to 5, 2 and 1. In blue, each log rounded down: 3, 2, 1, 0, one less at each halving. why it is allowed: Here is the number halved, from 2 up; for 11, is 3.
the move: rounding down never adds
the line:why it is allowed: For 11, 3 is at most 3.46.
the move: rounding down takes off less than 1
the line:why it is allowed: For 11, 4 is above 3.46.
the move: raise 2 to each side of line 2
the line:why it is allowed: 2 raised to a bigger power gives a bigger number. For 11, 8 is at most about 11.
the move: 2 to the log of n is n
the line:why it is allowed: By what a log is. For 11, 8 is at most 11.
the move: raise 2 to each side of line 3
the line:why it is allowed: As in line 4. For 11, about 11 is below 16.
the move: 2 to the log of n is n
the line:why it is allowed: As in line 5. For 11, 11 is below 16.
the move: halve both sides of line 5
the line:why it is allowed: For 11, 4 is at most 5.5, which is not whole.
the move: write the half as a power
the line:why it is allowed: Half a power of 2 has one 2 fewer. Half of 8 is 4.
the move: round the half down
the line:why it is allowed: is the half rounded down, 5 for 11. A whole number at most 5.5 is at most 5. The left side, 4 for 11, is whole, as is at least 1 for from 2 up.
the move: halve both sides of line 7
the line:why it is allowed: For 11, 5.5 is below 8.
the move: write the half as a power
the line:why it is allowed: As in line 9. Half of 16 is 8.
the move: round the half down
the line:why it is allowed: Rounding down never adds. For 11, 5 is below 8.
the move: take the log of line 10
the line:why it is allowed: A bigger number has a bigger log. For 11, the log of 4 is at most the log of 5.
the move: the log of a power of 2 is the power
the line:why it is allowed: For 11, the log of 4 is 2, at most about 2.32.
the move: take the log of line 13
the line:why it is allowed: As in line 14. For 11, the log of 5 is below the log of 8.
the move: the log of a power of 2 is the power
the line:why it is allowed: For 11, about 2.32 is below 3.
the move: round the log down
the line:the number at least below its log rounded down 11 8 16 3 5 4 8 2 2 2 4 1 1 1 2 0 Each halving takes 1 off the log rounded down. why it is allowed: By lines 15 and 17, the log of the half is at least one less than and below , so it rounds down to one less. For 11, about 2.32 rounds down to 2.
the move: use line 18 again and again
the line:why it is allowed: While the log rounded down is 1 or more, the number is at least 2 to the power 1, which is 2. So line 18 takes 1 off each halving, down to 0 after . For 11, 3, 2, 1, 0.
the move: a log rounded down to 0 belongs to 1
the line:why it is allowed: Such a log is at least 0 and below 1, so its number is at least 1 and below 2. It is 1.
why it is allowed: As in line 4, whole blocks end at 1 over 2 to the powers 1 to , that many blocks. For 12, 3.
the move: rounding takes off less than 1
the line:why it is allowed: Rounding down takes off less than 1, so putting less 1 for can only lower the right side. For 12, 2.5 becomes about 2.29.
the move: halve each part
the line:why it is allowed: Half of ( less 1) is half of , less one half.
the move: change the order
the line:why it is allowed: Adding and taking away go in any order.
the move: 1 less one half
the line:why it is allowed: 1 less one half is one half.
the move: drop the one half
the line:why it is allowed: Taking away one half makes the right side smaller. For 12, about 1.79.
the move: a floor
the line:- the ceiling,
- the harmonic sum
- the floor,
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, is at least one half times for every from 2. , read is in big omega of , says a fixed multiple of , above zero, is a floor of .
the move: ceiling and floor together
the line:why it is allowed: , read is in big theta of , says both: by lines 9 and 19, for every from 2, lies between one half and 2 times . It grows like .
why it is allowed: The bracket of line 10 is without its first 1. The box under this line shows how grows.
guess it, thenthe move: open the first bracket
the line:why it is allowed: Taking 1 away inside the bracket takes away .
guess it, thenthe move: gather
the line:why it is allowed: and add up to , 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.
guess it, thenthe move: how big the harmonic sum gets
the line:why it is allowed: The box at line 11 shows this, in its line 5.
guess it, thenthe move: a ceiling
the line:why it is allowed: Put line 14 into line 13.
guess it, thenthe move: open the bracket
the line:why it is allowed: Multiply by each of and 1.
guess it, thenthe move: gather
the line:why it is allowed: less leaves .
guess it, thenthe move: drop what is not positive
the line:why it is allowed: From 1 number on, is at most 0.
guess it, thenthe move: a simpler ceiling
the line:why it is allowed: is at most , and is not negative.
guess it, thenthe move: read it as a bound
the line:why it is allowed: By line 19.
guess it, thenthe move: a floor from the cheapest order
the line: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.
guess it, thenthe move: read it as a bound
the line:why it is allowed: By line 21.
guess it, thenthe move: ceiling and floor together
the line:why it is allowed: Lines 20 and 22 bound by the same growth, .
guess it, then
try it on small rows: over every order of 8 numbers, the average 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.
| step | the tree, level: numbers | what happens | numbers compared |
|---|---|---|---|
| 1 | Start with an empty tree, and 7 operations to do. | 0 | |
| 2 | 0: 40 | The tree is empty, so 40 goes at the top.0: 40 | 0 |
| 3 | 0: 40 | To put 20 in, start at the top.0: 40 | 0 |
| 4 | 0: 40 | 20 is smaller than 40, so go left.0: 40 | 1 |
| 5 | 0: 40; 1: 20 | The way runs out, so hang 20 to the left of 40.0: 40; 1: 20 | 1 |
| 6 | 0: 40; 1: 20 | To put 60 in, start at the top.0: 40; 1: 20 | 1 |
| 7 | 0: 40; 1: 20 | 60 is bigger than 40, so go right.0: 40; 1: 20 | 2 |
| 8 | 0: 40; 1: 20, 60 | The way runs out, so hang 60 to the right of 40.0: 40; 1: 20, 60 | 2 |
| 9 | 0: 40; 1: 20, 60 | To put 10 in, start at the top.0: 40; 1: 20, 60 | 2 |
| 10 | 0: 40; 1: 20, 60 | 10 is smaller than 40, so go left.0: 40; 1: 20, 60 | 3 |
| 11 | 0: 40; 1: 20, 60 | 10 is smaller than 20, so go left.0: 40; 1: 20, 60 | 4 |
| 12 | 0: 40; 1: 20, 60; 2: 10 | The way runs out, so hang 10 to the left of 20.0: 40; 1: 20, 60; 2: 10 | 4 |
| 13 | 0: 40; 1: 20, 60; 2: 10 | To put 30 in, start at the top.0: 40; 1: 20, 60; 2: 10 | 4 |
| 14 | 0: 40; 1: 20, 60; 2: 10 | 30 is smaller than 40, so go left.0: 40; 1: 20, 60; 2: 10 | 5 |
| 15 | 0: 40; 1: 20, 60; 2: 10 | 30 is bigger than 20, so go right.0: 40; 1: 20, 60; 2: 10 | 6 |
| 16 | 0: 40; 1: 20, 60; 2: 10, 30 | The way runs out, so hang 30 to the right of 20.0: 40; 1: 20, 60; 2: 10, 30 | 6 |
| 17 | 0: 40; 1: 20, 60; 2: 10, 30 | To put 50 in, start at the top.0: 40; 1: 20, 60; 2: 10, 30 | 6 |
| 18 | 0: 40; 1: 20, 60; 2: 10, 30 | 50 is bigger than 40, so go right.0: 40; 1: 20, 60; 2: 10, 30 | 7 |
| 19 | 0: 40; 1: 20, 60; 2: 10, 30 | 50 is smaller than 60, so go left.0: 40; 1: 20, 60; 2: 10, 30 | 8 |
| 20 | 0: 40; 1: 20, 60; 2: 10, 30, 50 | The way runs out, so hang 50 to the left of 60.0: 40; 1: 20, 60; 2: 10, 30, 50 | 8 |
| 21 | 0: 40; 1: 20, 60; 2: 10, 30, 50 | To put 70 in, start at the top.0: 40; 1: 20, 60; 2: 10, 30, 50 | 8 |
| 22 | 0: 40; 1: 20, 60; 2: 10, 30, 50 | 70 is bigger than 40, so go right.0: 40; 1: 20, 60; 2: 10, 30, 50 | 9 |
| 23 | 0: 40; 1: 20, 60; 2: 10, 30, 50 | 70 is bigger than 60, so go right.0: 40; 1: 20, 60; 2: 10, 30, 50 | 10 |
| 24 | 0: 40; 1: 20, 60; 2: 10, 30, 50, 70 | The way runs out, so hang 70 to the right of 60.0: 40; 1: 20, 60; 2: 10, 30, 50, 70 | 10 |
| 25 | 0: 40; 1: 20, 60; 2: 10, 30, 50, 70 | Done. The tree holds 7 numbers.0: 40; 1: 20, 60; 2: 10, 30, 50, 70 | 10 |
In all, 10 numbers compared. The formula from section 4, , gives at : 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 , in any order; puts cost 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 . 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
| question | how TreeMap asks it | a hash table |
|---|---|---|
| the smallest key | firstKey() | reads every slot |
| the next key after 42 | higherKey(42) | reads every slot |
| every key from 20 to 50, in order | subMap(20, true, 50, true) | reads every slot, then sorts |
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 numbers in, one at a time. A chain's look, like a comparison here, weighs one number against the one in hand.
| way | n shuffled numbers in, on average | n numbers in order | extra memory | reach for it when |
|---|---|---|---|---|
| a search tree | comparisons, about 10,986 at 1,000 | comparisons, a path | two links beside each number | numbers arrive shuffled, or the tree is kept balanced |
| a chain kept in order | about a quarter of times looks, about 250,743 at 1,000 | every number already in, each put: 499,500 looks at 1,000 | one link beside each number | you cut or join whole runs of numbers at once |
- a chain kept in order, from the linked list's page
- a search tree,