AVL tree
Level 3 of 3
Also called Self-balancing binary search tree and Adelson-Velsky and Landis tree.
how it works
The idea in a few sentences and three pictures, then one run, moment by moment.
An AVL tree keeps a search tree short as numbers go in. A number goes in as in the plain tree: start at the top, smaller goes left, bigger goes right, and hang it where the way runs out. Each number met is one comparison, this page's count. Then climb back towards the top, comparing each place's two sides: how many levels each reaches. Where one side is two levels higher, turn there to lift it. A side that leans inwards is turned outwards first, a double turn, which is two turns. Weighing levels compares no numbers, so the climb adds no comparison. A put mends at most once, with a single turn or a double. The turned side gets back the levels it had before the put, so every place above sees what it saw before. Sebastian Bourges' books put it: 'the descent is unchanged, and the repair rides home on the return.' (volume two, chapter 20). The run after these pictures puts in 10, 20, 30, 40, 50, 60 and 70, in order.
step 8 of 14
30 is bigger than 10, so go right.
numbers compared: 1
step 9 of 14
30 is bigger than 20, so go right.
numbers compared: 2
step 10 of 14
The way runs out, so hang 30 to the right of 20.
numbers compared: 2
step 12 of 14
At 10, the left side is empty and the right side 2 levels high: two levels apart, so the tree must turn.
numbers compared: 2
step 13 of 14
Turn left at 10: 20 moves up into its place, and 10 hangs to its left.
numbers compared: 2
step 10 of 15
The way runs out, so hang 30 to the right of 20.
numbers compared: 2
step 12 of 15
At 40, the left side is 2 levels high and the right side empty: two levels apart, so the tree must turn.
numbers compared: 2
step 13 of 15
Turn left at 20: 30 moves up into its place, and 20 hangs to its left.
numbers compared: 2
step 14 of 15
Turn right at 40: 30 moves up into its place, and 40 hangs to its right.
numbers compared: 2
step 35 of 37
At 20, the left side is one level high and the right side 3 levels high: two levels apart, so the tree must turn.
numbers compared: 3
step 36 of 37
Turn left at 20: 40 moves up into its place, and 20 hangs to its left.
numbers compared: 3
step 10 of 45
The way runs out, so hang 30 to the right of 20.
what it remembers to know where it is
- doing operation
- 3
- looking at
- not yet
- in the tree
- 3
Where it says not yet, nothing is held there at that moment.
step 12 of 45
At 10, the left side is empty and the right side 2 levels high: two levels apart, so the tree must turn.
what it remembers to know where it is
- doing operation
- 3
- looking at
- 10
- in the tree
- 3
step 13 of 45
Turn left at 10: 20 moves up into its place, and 10 hangs to its left.
what it remembers to know where it is
- doing operation
- 3
- looking at
- not yet
- in the tree
- 3
Where it says not yet, nothing is held there at that moment.
step 26 of 45
At 30, the left side is empty and the right side 2 levels high: two levels apart, so the tree must turn.
what it remembers to know where it is
- doing operation
- 5
- looking at
- 30
- in the tree
- 5
step 27 of 45
Turn left at 30: 40 moves up into its place, and 30 hangs to its left.
what it remembers to know where it is
- doing operation
- 5
- looking at
- not yet
- in the tree
- 5
Where it says not yet, nothing is held there at that moment.
step 35 of 45
At 20, the left side is one level high and the right side 3 levels high: two levels apart, so the tree must turn.
what it remembers to know where it is
- doing operation
- 6
- looking at
- 20
- in the tree
- 6
step 36 of 45
Turn left at 20: 40 moves up into its place, and 20 hangs to its left.
what it remembers to know where it is
- doing operation
- 6
- looking at
- not yet
- in the tree
- 6
Where it says not yet, nothing is held there at that moment.
step 44 of 45
Turn left at 50: 60 moves up into its place, and 50 hangs to its left.
what it remembers to know where it is
- doing operation
- 7
- looking at
- not yet
- in the tree
- 7
Where it says not yet, nothing is held there at that moment.
the steps, in plain words
choose a step to mark the Python, a programming language, that does it
- start with an empty treePython line 50
- start at the topPython line 52
- smaller goes left, bigger goes right, until the way runs outPython lines 53, 54, 55 and 56
- hang the number there; a number already in is not put in againPython lines 57, 58, 59, 60, 61, 62, 63, 64, 65, 66 and 67
- climb back towards the top, comparing each place's two sidesPython lines 11, 12, 13, 16, 17, 18, 68, 69, 70, 71, 72 and 73
- where one side is two levels higher, turn there to lift itPython lines 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 74, 77, 78, 81, 82, 83, 84, 85, 86, 87 and 88
- if that side leans inwards, turn it outwards firstPython lines 75, 76, 79 and 80
the same in Python
The steps in plain words are what to learn. Python is a programming language, and the code below does the same steps, for those who code. Python numbers the places in a list from 0, not 1: the first number is numbers[0], the second numbers[1], and so on.
class Place:
"""One place of the tree: a number, a place on each side, its levels."""
def __init__(self, value):
self.value = value # the number it holds
self.left = None # the smaller numbers hang here
self.right = None # the bigger numbers hang here
self.levels = 1 # levels from here down, this one included
def levels(place):
"""How many levels hang from this place, itself included; 0 for none."""
return 0 if place is None else place.levels
def mend(place):
"""Work out a place's levels again from its two sides."""
place.levels = 1 + max(levels(place.left), levels(place.right))
def turn(place, way):
"""Turn at this place, 'left' or 'right': its child on the other side
moves up, and this place hangs below that child. Returns the child."""
if way == 'right':
up = place.left
place.left, up.right = up.right, place
else:
up = place.right
place.right, up.left = up.left, place
mend(place) # the lower place first: the upper one reads its levels
mend(up)
return up
def shape(place):
"""The tree from this place down, as [left, number, right]."""
if place is None:
return None
return [shape(place.left), place.value, shape(place.right)]
def avl_tree(numbers):
"""Put each number into an AVL tree, in turn.
Returns the tree as [left, number, right], each side the same shape,
None where nothing hangs. A number already in is not put in again.
Each comparison weighs the number at one place against the number put
in; comparing two sides' levels is no comparison of numbers.
"""
top = None # an empty tree
for number in numbers:
path, place = [], top # start at the top
while place is not None and place.value != number: # one comparison
went_left = number < place.value # smaller goes left
path.append((place, went_left))
place = place.left if went_left else place.right
if place is not None: # already in: nothing changes
continue
child = Place(number) # hang it where the way ran out
if not path:
top = child
continue
parent, went_left = path[-1]
if went_left:
parent.left = child
else:
parent.right = child
for depth in range(len(path) - 1, -1, -1): # climb back to the top
place = path[depth][0]
lean = levels(place.left) - levels(place.right)
if abs(lean) < 2: # the two sides are within one level
mend(place)
continue
if lean == 2: # the left side is two levels higher
if levels(place.left.right) > levels(place.left.left):
place.left = turn(place.left, 'left') # leans inwards
lifted = turn(place, 'right')
else: # the right side is two levels higher
if levels(place.right.left) > levels(place.right.right):
place.right = turn(place.right, 'right') # leans inwards
lifted = turn(place, 'left')
if depth == 0:
top = lifted
elif path[depth - 1][1]:
path[depth - 1][0].left = lifted
else:
path[depth - 1][0].right = lifted
break # one turn, single or double, mends the whole tree
return shape(top)
how it scales
How the comparisons grow, from ten numbers to a hundred thousand, each put into an empty tree one at a time. Two orders: middle first, level by level, and a shuffle. The plot and tables call a comparison a number compared, as the watch page does.
Each step across or up is ten times the one before, a log-log plot. Both orders climb a little more than one step up for each step across: 480 and about 539 comparisons at 100 numbers, 7,987 and about 8,723 at 1,000. 480 to 7,987 is about 17 times, and the factor shrinks further right. Near 100 to 1,000 numbers, a shuffle costs about a tenth more than middle first, and less further right. Each shuffle point is the mean of 20 shuffles. No formula is worked out for the average, so it is drawn as points only.
numbers compared, ten times more at each mark up
, how many numbers are in the tree, ten times more at each mark to the right
- a shuffle, every order as likelypoints only, each measured by a real run, since no single formula for the numbers compared of this row is worked out here
- middle first, level by level, the cheapest order foundsolid where measured by running it; dashed where its formula carries it on to ten millionslope 1.1: ten times n, about 12 times the work
| numbers compared | time | |
|---|---|---|
| 1,000 | 7,987 | about 8 microseconds |
| 100,000 | 1,468,946 | about 1.5 milliseconds |
| 10,000,000 | 213,222,809 | about 213 milliseconds |
The numbers compared are the same on any computer. The times are not: a real computer may be faster or slower than a billion a second.
make these counts yourself
Copy this script and run it with Python 3.12 or later. It counts the same steps as the plot. Where a count depends on a random shuffle, yours will differ a little.
"""Count an AVL tree's comparisons yourself, as the plot on this page does.
Run it with Python 3.12 or later. For each size n it puts n different
numbers into an empty tree, one at a time, and prints the comparisons for
the middle first, level by level (the cheapest order found), for 1 to n in
order, and the average over 20 shuffles. A comparison weighs the number at
one place against the number put in; comparing two sides' levels is not
one. The counts are the same on any computer; only the time differs.
"""
import random
class Counted:
"""A number that counts the comparisons made with it."""
comparisons = 0
def __init__(self, value):
self.value = value
def __ne__(self, other):
Counted.comparisons += 1 # is this the number? one comparison
return self.value != other.value
def __lt__(self, other):
return self.value < other.value # which way: part of the same one
class Place:
"""One place of the tree: a number, a place on each side, its levels."""
def __init__(self, value):
self.value = value # the number it holds
self.left = None # the smaller numbers hang here
self.right = None # the bigger numbers hang here
self.levels = 1 # levels from here down, this one included
def levels(place):
"""How many levels hang from this place, itself included; 0 for none."""
return 0 if place is None else place.levels
def mend(place):
"""Work out a place's levels again from its two sides."""
place.levels = 1 + max(levels(place.left), levels(place.right))
def turn(place, way):
"""Turn at this place, 'left' or 'right': its child on the other side
moves up, and this place hangs below that child. Returns the child."""
if way == 'right':
up = place.left
place.left, up.right = up.right, place
else:
up = place.right
place.right, up.left = up.left, place
mend(place) # the lower place first: the upper one reads its levels
mend(up)
return up
def shape(place):
"""The tree from this place down, as [left, number, right]."""
if place is None:
return None
return [shape(place.left), place.value, shape(place.right)]
def avl_tree(numbers):
"""Put each number into an AVL tree, in turn.
Returns the tree as [left, number, right], each side the same shape,
None where nothing hangs. A number already in is not put in again.
Each comparison weighs the number at one place against the number put
in; comparing two sides' levels is no comparison of numbers.
"""
top = None # an empty tree
for number in numbers:
path, place = [], top # start at the top
while place is not None and place.value != number: # one comparison
went_left = number < place.value # smaller goes left
path.append((place, went_left))
place = place.left if went_left else place.right
if place is not None: # already in: nothing changes
continue
child = Place(number) # hang it where the way ran out
if not path:
top = child
continue
parent, went_left = path[-1]
if went_left:
parent.left = child
else:
parent.right = child
for depth in range(len(path) - 1, -1, -1): # climb back to the top
place = path[depth][0]
lean = levels(place.left) - levels(place.right)
if abs(lean) < 2: # the two sides are within one level
mend(place)
continue
if lean == 2: # the left side is two levels higher
if levels(place.left.right) > levels(place.left.left):
place.left = turn(place.left, 'left') # leans inwards
lifted = turn(place, 'right')
else: # the right side is two levels higher
if levels(place.right.left) > levels(place.right.right):
place.right = turn(place.right, 'right') # leans inwards
lifted = turn(place, 'left')
if depth == 0:
top = lifted
elif path[depth - 1][1]:
path[depth - 1][0].left = lifted
else:
path[depth - 1][0].right = lifted
break # one turn, single or double, mends the whole tree
return shape(top)
def cheapest(n):
"""1 to n, middle first, level by level: every stretch of a level split
at its middle, left to right, before the next level starts."""
order, stretches = [], [(1, n)]
for low, high in stretches: # the list grows as it is read
if low > high:
continue
middle = (low + high) // 2
order.append(middle)
stretches += [(low, middle - 1), (middle + 1, high)]
return order
def count(numbers):
"""How many comparisons the tree makes putting these numbers in, in turn."""
Counted.comparisons = 0
avl_tree([Counted(number) for number in numbers])
return Counted.comparisons
if __name__ == "__main__":
random.seed(1)
print(f"{'n':>6} {'middle first':>13} {'in order':>10} {'shuffled':>10}")
for n in [10, 100, 1000]:
row = list(range(1, n + 1))
shuffles = []
for _ in range(20):
random.shuffle(row)
shuffles.append(count(row))
print(f"{n:>6} {count(cheapest(n)):>13} {count(range(1, n + 1)):>10} {sum(shuffles) / 20:>10.1f}")
best, worst and average
A put meets one number on each level above where it hangs, and the turns keep every tree short. So the order barely moves the cost. Middle first, level by level, is the cheapest order found. Every order of 1 to 8 numbers was tried, 46,233 in all, and none costs less. There is no worst column: this page finds the dearest order only by trying every order of short rows. Section 4 bounds every order.
A case is one kind of input, the thing the method is given, such as numbers in order, however many. A bound says how fast that case's cost grows as more numbers go in.
The counts are in the grid. A count is often the sum of pieces that grow at different speeds, and on long inputs the fastest-growing piece swamps the rest. For example, a count of half of n times n, less half of n: at 2,000 items, 2,000,000 less 1,000. So how a cost grows is what tells one method from another, and the bounds keep just that.
| bestmiddle first, level by level, the cheapest order found | averagea shuffle, every order as likely | |
|---|---|---|
| numbers compared | , with the rounded down: 480 for 100 | measured, between and : at 100, between about 83 and 1,329, and about 539 measured |
| how the numbers compared grow in each case | ||
| tight, | ||
| ceiling, | ||
| floor, | ||
extra memory: two links and its levels beside each number
Extra memory is the room it needs on top of the input itself, while it runs.
| order | numbers put in | comparisons by each put | in all | the plain tree's |
|---|---|---|---|---|
| in order | 10, 20, 30, 40, 50, 60, 70 | 0, 1, 2, 2, 3, 3, 3 | 14 | 21 |
| back to front | 70, 60, 50, 40, 30, 20, 10 | 0, 1, 2, 2, 3, 3, 3 | 14 | 21 |
| a shuffle | 30, 60, 10, 50, 20, 70, 40 | 0, 1, 1, 2, 2, 2, 3 | 11 | 11 |
| middle first, level by level | 40, 20, 60, 10, 30, 50, 70 | 0, 1, 1, 2, 2, 2, 2 | 10 | 10 |
| numbers | orders tried | cheapest | average | dearest | in order |
|---|---|---|---|---|---|
| 5 | 120 | 6 | 7.07 | 8 | 8 |
| 6 | 720 | 8 | 9.73 | 11 | 11 |
| 7 | 5,040 | 10 | 12.59 | 14 | 14 |
| 8 | 40,320 | 13 | 15.66 | 18 | 17 |
step 33 of 37
The way runs out, so hang 10 to the left of 20.
numbers compared: 3
where the formula comes from
Each count above, worked out line by line. Each reason names the line it uses, and each 'where does this come from?' box opens a fact from another page.
the move: price a number by its level
the line:step 29 of 35
To put 7 in, start at the top.
numbers compared: 0
step 30 of 35
7 is bigger than 4, so go right.
numbers compared: 1
step 31 of 35
7 is bigger than 6, so go right.
numbers compared: 2
step 32 of 35
The way runs out, so hang 7 to the right of 6.
numbers compared: 2
step 33 of 35
At 6, the left side is one level high and the right side one level high, so it is balanced.
numbers compared: 2
step 34 of 35
At 4, the left side is 2 levels high and the right side 2 levels high, so it is balanced.
numbers compared: 2
1 to 7, middle first, level by level. 7 meets 4 and 6, 2 comparisons, and hangs on level 2. Climbing back, 6 and 4 are balanced, so nothing turns. why it is allowed: The top is level 0. A put meets one number on each level above where it hangs, and none on its own level. The climb back weighs levels, not numbers.
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: see middle first fill the levels
the line:1 to 8, middle first, a row a level. Each heavy box is a stretch, its middle in blue. At the right, the numbers below each level, line 7's terms. level stretches numbers in each 0 1 to 8 8 1 1 to 3; 5 to 8 3; 4 2 1; 3; 5; 7 and 8 1; 1; 1; 2 3 8 1 Taking a middle out leaves two stretches within one number of each other, so no stretch runs out before its level is full. why it is allowed: A stretch is the run of numbers between two already in, or between one and the end of the row. For 1 to 7, 3 is the middle of the stretch between 2 and 4: it meets 4, then 2, and hangs right of 2, on level 2. So each number of level is the middle of a stretch whose ends are in, the deeper end one level up, and it hangs below that end. In the drawing, each row is a level.
guess it, thenthe move: see nothing turn
the line:why it is allowed: While level fills, every level above it is full. So each side of a place higher up reaches the level just above , and at most one level more. A place on the level just above has at most one level below it. Putting 5 into 4, 2, 6, 1 and 3: 4's left side reaches 2 levels, and its right side goes from 1 to 2. Nothing turns. Lines 3 and 4 hold together, put by put.
guess it, thenthe move: find the last level
the line:why it is allowed: Levels 0 to hold numbers, fewer than , as is at most . Levels 0 to hold one less than , so at least , as is less than . The page on halving and logarithms shows both, and the box at line 9 the sums. For 7, is 2: levels 0 and 1 hold 3, fewer than 7, and levels 0 to 2 hold 7.
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 lines 3 and 5, levels 0 to are full, holding numbers by line 2, and every other number hangs below. For 7, 7 less 1, which is 6, below level 0, and 7 less 3, which is 4, below level 1, as in line 6's table.
guess it, thenthe move: add the levels
the line:why it is allowed: is the comparisons of middle first, level by level. By lines 6 and 7, each level from 0 to adds the numbers below it. By line 5, nothing hangs below 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 10 each hold one .
guess it, thenthe move: add the doublings again
the line:why it is allowed: By the box at line 9, the doublings from 1 add up to one less than the next doubling. Here the first 1 is missing, so it is two less. For 7 numbers, 2 + 4 is 6, which is 8 less 2.
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 6's table.
guess it, thenthe move: a ceiling
the line:why it is allowed: Each of the terms of line 10 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 15, the fixed multiple 1, from 1 number on.
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 10 but the last is more than half of , and the last is at least 1. From 2 numbers on, line 10 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 17 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 20 into line 19. A third of , times half of , is a sixth of .
guess it, thenthe move: read it as a bound
the line:why it is allowed: By line 21, the fixed multiple a sixth, from 8 numbers on.
guess it, thenthe move: ceiling and floor together
the line:why it is allowed: Lines 16 and 22 bound by the same growth, .
guess it, then
try it with a small : at , line 8 gives , which you can work out by hand
the move: price a put by the levels
the line:step 29 of 37
To put 10 in, start at the top.
numbers compared: 0
step 30 of 37
10 is smaller than 50, so go left.
numbers compared: 1
step 31 of 37
10 is smaller than 30, so go left.
numbers compared: 2
step 32 of 37
10 is smaller than 20, so go left.
numbers compared: 3
step 33 of 37
The way runs out, so hang 10 to the left of 20.
numbers compared: 3
50, 30, 60, 20, 40 and 70 stand on 3 levels. 10 meets 50, 30 and 20, one a level, 3 comparisons, the most 3 levels allow. why it is allowed: Its walk goes down one level at each number it meets, and hangs below the last. So a tree of levels costs a put at most comparisons.
the move: ask the fewest numbers, not the most levels
the line:step 33 of 37
The way runs out, so hang 10 to the left of 20.
numbers compared: 3
step 34 of 37
At 20, the left side is one level high and the right side empty, so it is balanced.
numbers compared: 3
step 35 of 37
At 30, the left side is 2 levels high and the right side one level high, so it is balanced.
numbers compared: 3
step 36 of 37
At 50, the left side is 3 levels high and the right side 2 levels high, so it is balanced.
numbers compared: 3
The thinnest tree of 4 levels holds 7 numbers. Climbing back from 10, at 20, 30 and 50 the left side is one level higher than the right. levels fewest numbers one more 1 1 2 1.41 2 2 3 2 3 4 5 2.83 4 7 8 4 5 12 13 5.66 6 20 21 8 Each fewest is the two above it added, plus 1. One more than each stays ahead of the last column, as line 5 shows. why it is allowed: The top has one side of levels, or the tree would be shorter. The other side is within one level, so at least . Each side holds fewest when it too is a thinnest tree, and the 1 is the top. So 1, 2, then 2 + 1 + 1, which is 4, then 7, then 12.
guess it, thenthe move: add 1 to both
the line:why it is allowed: Add 1 to line 2 and share the 2 out, one to each bracket. In the table, 13 is 8 plus 5.
guess it, thenthe move: at least double, two levels down
the line:why it is allowed: By line 2, a thinnest tree of levels holds a thinnest tree of and more, so line 3's first bracket is at least its second. In the table, 13 is at least twice 5.
guess it, thenthe move: climb from the start
the line:why it is allowed: It holds at 1 and 2 levels, as the table's first rows show. By line 4, two levels more at least double the left side and exactly double the right. So it holds at every : the climb of the page on proof by induction.
guess it, thenthe move: turn it round
the line:why it is allowed: A tree of numbers on levels holds at least , so is at least by line 5. So half of is at most , by the page on halving and logarithms, and at most twice that. For 12 numbers, at most about 7.4 levels; the table's thinnest has 5.
guess it, thenthe move: price put k
the line:why it is allowed: Put goes into a tree holding one number fewer than . So by line 6, with that number as , is , and it has at most levels. By line 1, at most that many comparisons. Put 7 goes into 6 numbers: at most about 5.6 levels.
guess it, thenthe move: add the puts
the line:why it is allowed: adds line 7's ceiling over the puts. Put 1 costs 0, which is . For 7, about 24.6.
guess it, thenthe move: read it
the line:numbers orders tried dearest ceiling 5 120 8 13.81 6 720 11 18.98 7 5,040 14 24.60 8 40,320 18 30.60 Every order of 1 to n tried. The dearest always lies under the ceiling. why it is allowed: Lines 1 to 8 hold for every order. The table tries every order of short rows, and the dearest stays well under .
guess it, thenthe move: a simpler ceiling
the line:why it is allowed: Each of the terms of line 8 is at most the last, .
guess it, thenthe move: read it as a bound
the line:why it is allowed: By line 10, stays under twice .
guess it, then
try it with a small : at , line 8 gives , about 24.6
the move: find the nearest empty spot
the line:step 29 of 35
To put 55 in, start at the top.
numbers compared: 0
step 30 of 35
55 is bigger than 50, so go right.
numbers compared: 1
step 31 of 35
55 is smaller than 60, so go left.
numbers compared: 2
step 32 of 35
The way runs out, so hang 55 to the left of 60.
numbers compared: 2
50, 30, 60, 20, 40 and 70 stand on 3 levels. The nearest empty spot, left of 60, is 2 down, at least half of 3. 55 meets 50 and 60. why it is allowed: It holds with no levels, the top itself the empty spot, and with 1 level, every spot 1 down. A taller tree has one side a level shorter than the tree. The rule keeps the other within one level of it, so each side is at most 2 levels shorter. Say 4 levels: each side has at least 2, so a spot is at least 1 down inside its side, 2 from the top, half of 4. Each climbs from 2 levels fewer the same way, the climb of the page on proof by induction.
the move: count the levels a tree needs
the line:why it is allowed: Level 0 holds 1 number, level 1 at most 2, level 2 at most 4, each level at most double the one above. So 3 levels hold at most 7, one less than 8, as the box at line 9 of the question on the cheapest order shows. So doublings of 1 reach at least , and is at least , by the page on halving and logarithms. 7 numbers need 3 levels.
guess it, thenthe move: price put k from below
the line:why it is allowed: Put goes into a tree holding one number fewer than , so of at least levels by line 2. By line 1 it hangs at least half that far down, meeting one number a level.
guess it, thenthe move: add the puts
the line:why it is allowed: adds line 3's floor over the puts. For 7, about 6.15.
guess it, thenthe move: read it
the line:numbers orders tried floor cheapest 5 120 3.45 6 6 720 4.75 8 7 5,040 6.15 10 8 40,320 7.65 13 Every order of 1 to n tried. The cheapest always lies above the floor. why it is allowed: Lines 1 to 4 hold for every order. The table tries every order of short rows, and the cheapest stays above .
guess it, thenthe move: write the sum as one log
the line:where does this come from?
question 4 of the page the sorting floorHow does grow? the move: name the log
the line:why it is allowed: Let be the log to base 2 of , for from 4 as lines 12 and 15 need. For 8, about 15.30.
the move: factors at most n
the line:why it is allowed: multiplies whole numbers, each at most . Putting for each gives , read to the power , no smaller. For 8, 40,320 against 16,777,216.
the move: bigger number, bigger log
the line:why it is allowed: On a number line of powers of 2, 16 stands right of 8, and its log, 4, right of 8's log, 3. Any two numbers go the same way, as the page halving and logarithms shows, so line 2 holds for the logs.
the move: into line 1
the line:why it is allowed: By line 3, as is the log of .
the move: log of a power
the line:why it is allowed: For 8: 8 is three 2s, so 8 to the power 8 is 24 2s, since multiplying powers of 2 adds the powers. Each number is 2 raised to its log, so the log of a product adds the logs. is a product of factors, each , so its log is times .
the move: keep the top half
the line:why it is allowed: Drop the factors 1 to half of rounded down; each is at least 1, so the product gets no bigger. Half of rounded down and rounded up add up to , as 3 and 4 for 7. So are kept, read half of rounded up.
the move: half of n for each
the line:for 8 multiplied 8 down to 1 40,320 8 × 7 × 6 × 5 1,680 4 × 4 × 4 × 4 256 Drop 4 down to 1, then put 4, half of 8, for each factor kept. why it is allowed: Each kept factor is above half of , so putting half of for each gives no bigger product.
the move: bigger number, bigger log
the line:why it is allowed: As in line 3.
the move: into line 1
the line:why it is allowed: By line 8, as is the log of .
the move: log of a power
the line:why it is allowed: As in line 5. For 8, 4 times 2.
the move: rounding up
the line:why it is allowed: Rounding up makes no smaller, as 3.5 goes up to 4.
the move: log of half of n
the line:why it is allowed: From 4 on, half of is at least 2, whose log is 1; by line 3, bigger numbers have bigger logs.
the move: drop the rounding
the line:why it is allowed: By line 11, half of is at most , as 3.5 against 4 for 7. Each multiplies the log of half of , above zero by line 12, so putting half of in line 10 makes it no bigger.
the move: halving takes 1 off
the line:why it is allowed: is 2 times half of , and the log of 2 is 1. So by line 5 the log of half of is . For 8, the log of 4 is 3 less 1.
the move: a fact about n
the line:why it is allowed: From 4 on, is at least 2, so half of it is at least 1, and taking 1 away leaves at least half. For 8, 1.5 against 2.
the move: the smaller part
the line:why it is allowed: By line 15, putting half of for in line 14 makes it no bigger, as in line 13. For 8, 4 times 1.5, 6.
the move: multiply out
the line:- the log of
- a quarter of
The log of between the other two, from 1 to 10 numbers. At 8: 24, about 15.30, and 6. why it is allowed: Half of times half of .
the move: a ceiling
the line:why it is allowed: , read is in big O of , says a fixed multiple of it is a ceiling of . By line 5, 1 times it, from 4 on.
the move: a floor
the line:why it is allowed: , read big omega, says a fixed multiple, above zero, is a floor of , a floor on growth, not the sorting floor. By line 17, a quarter, from 4 on.
the move: both
the line:why it is allowed: , read big theta, says both, by lines 18 and 19. grows like .
why it is allowed: The log of a product adds the logs, as the box under this line uses. The log of 2 times 4, which is 8, is 3, which is 1 + 2.
guess it, thenthe move: use how that log grows
the line:why it is allowed: The box at line 6 shows the log is at least a quarter of from 4 on, at its line 17. Half of a quarter is an eighth.
guess it, thenthe move: read it as a bound
the line:why it is allowed: By line 7, the fixed multiple an eighth, from 4 on. With the question on the ceiling, every order, the dearest too, costs .
guess it, then
try it with a small : at , line 4 gives , about 6.15
the move: a floor from every order
the line:why it is allowed: No order costs less than , by lines 5 and 7 of the question on the floor, so neither does their average.
the move: read it as a bound
the line:why it is allowed: By line 1, the fixed multiple an eighth, from 4 on.
guess it, thenthe move: a ceiling from every order
the line:why it is allowed: No order costs more than , by lines 9 and 10 of the question on the ceiling, so neither does their average.
guess it, thenthe move: read it as a bound
the line:why it is allowed: By line 3, the fixed multiple 2.
guess it, thenthe move: ceiling and floor together
the line:why it is allowed: Lines 2 and 4 bound by the same growth, .
guess it, then
try it on small rows: over every order of 7 numbers, the average is about 12.59
count it yourself
Count every comparison as 40, 20, 60, 10, 30, 50 and 70 go into an empty tree, middle first, level by level. Nothing turns.
| step | the tree, level: numbers | what happens | numbers compared | turns |
|---|---|---|---|---|
| 1 | Start with an empty tree, and 7 numbers to put in. | 0 | 0 | |
| 2 | 0: 40 | The tree is empty, so 40 goes at the top.0: 40 | 0 | 0 |
| 3 | 0: 40 | To put 20 in, start at the top.0: 40 | 0 | 0 |
| 4 | 0: 40 | 20 is smaller than 40, so go left.0: 40 | 1 | 0 |
| 5 | 0: 40; 1: 20 | The way runs out, so hang 20 to the left of 40.0: 40; 1: 20 | 1 | 0 |
| 6 | 0: 40; 1: 20 | At 40, the left side is one level high and the right side empty, so it is balanced.0: 40; 1: 20 | 1 | 0 |
| 7 | 0: 40; 1: 20 | To put 60 in, start at the top.0: 40; 1: 20 | 1 | 0 |
| 8 | 0: 40; 1: 20 | 60 is bigger than 40, so go right.0: 40; 1: 20 | 2 | 0 |
| 9 | 0: 40; 1: 20, 60 | The way runs out, so hang 60 to the right of 40.0: 40; 1: 20, 60 | 2 | 0 |
| 10 | 0: 40; 1: 20, 60 | At 40, the left side is one level high and the right side one level high, so it is balanced.0: 40; 1: 20, 60 | 2 | 0 |
| 11 | 0: 40; 1: 20, 60 | To put 10 in, start at the top.0: 40; 1: 20, 60 | 2 | 0 |
| 12 | 0: 40; 1: 20, 60 | 10 is smaller than 40, so go left.0: 40; 1: 20, 60 | 3 | 0 |
| 13 | 0: 40; 1: 20, 60 | 10 is smaller than 20, so go left.0: 40; 1: 20, 60 | 4 | 0 |
| 14 | 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 | 0 |
| 15 | 0: 40; 1: 20, 60; 2: 10 | At 20, the left side is one level high and the right side empty, so it is balanced.0: 40; 1: 20, 60; 2: 10 | 4 | 0 |
| 16 | 0: 40; 1: 20, 60; 2: 10 | At 40, the left side is 2 levels high and the right side one level high, so it is balanced.0: 40; 1: 20, 60; 2: 10 | 4 | 0 |
| 17 | 0: 40; 1: 20, 60; 2: 10 | To put 30 in, start at the top.0: 40; 1: 20, 60; 2: 10 | 4 | 0 |
| 18 | 0: 40; 1: 20, 60; 2: 10 | 30 is smaller than 40, so go left.0: 40; 1: 20, 60; 2: 10 | 5 | 0 |
| 19 | 0: 40; 1: 20, 60; 2: 10 | 30 is bigger than 20, so go right.0: 40; 1: 20, 60; 2: 10 | 6 | 0 |
| 20 | 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 | 0 |
| 21 | 0: 40; 1: 20, 60; 2: 10, 30 | At 20, the left side is one level high and the right side one level high, so it is balanced.0: 40; 1: 20, 60; 2: 10, 30 | 6 | 0 |
| 22 | 0: 40; 1: 20, 60; 2: 10, 30 | At 40, the left side is 2 levels high and the right side one level high, so it is balanced.0: 40; 1: 20, 60; 2: 10, 30 | 6 | 0 |
| 23 | 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 | 0 |
| 24 | 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 | 0 |
| 25 | 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 | 0 |
| 26 | 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 | 0 |
| 27 | 0: 40; 1: 20, 60; 2: 10, 30, 50 | At 60, the left side is one level high and the right side empty, so it is balanced.0: 40; 1: 20, 60; 2: 10, 30, 50 | 8 | 0 |
| 28 | 0: 40; 1: 20, 60; 2: 10, 30, 50 | At 40, the left side is 2 levels high and the right side 2 levels high, so it is balanced.0: 40; 1: 20, 60; 2: 10, 30, 50 | 8 | 0 |
| 29 | 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 | 0 |
| 30 | 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 | 0 |
| 31 | 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 | 0 |
| 32 | 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 | 0 |
| 33 | 0: 40; 1: 20, 60; 2: 10, 30, 50, 70 | At 60, the left side is one level high and the right side one level high, so it is balanced.0: 40; 1: 20, 60; 2: 10, 30, 50, 70 | 10 | 0 |
| 34 | 0: 40; 1: 20, 60; 2: 10, 30, 50, 70 | At 40, the left side is 2 levels high and the right side 2 levels high, so it is balanced.0: 40; 1: 20, 60; 2: 10, 30, 50, 70 | 10 | 0 |
| 35 | 0: 40; 1: 20, 60; 2: 10, 30, 50, 70 | Done. The tree holds 7 numbers, and it is balanced.0: 40; 1: 20, 60; 2: 10, 30, 50, 70 | 10 | 0 |
In all, 10 numbers compared. The formula from section 4, , gives at : the same.
where you meet it
Two programs keep keys in AVL trees, musl and OpenZFS.
musl's tsearch
musl, a C library, the ready-made code C programs call, builds its tsearch as an AVL tree, each place keeping its levels. So a search, put or take meets at most about twice keys, by section 4.
source: musl's source, src/search/tsearch.c (opens in a new tab)
OpenZFS
OpenZFS, a file system, carries its own general AVL tree, avl.c, which its other parts use to keep things in order in memory.
source: OpenZFS's source, module/avl/avl.c (opens in a new tab)
| 1,000 numbers put in | the plain search tree | an AVL tree |
|---|---|---|
| in order | 499,500 | 8,977 |
| shuffled, the mean of 20 | about 11,190 | about 8,723 |
| middle first, level by level | 7,987 | 7,987 |
what is used instead
Most languages use a red-black tree instead, as Java's TreeMap and C++'s std::map do. Its rule is looser, so its trees may stand taller, but a put turns less on average. Sebastian Bourges' books: 'the stricter the balance rule, the shallower the tree and the more work each update does.' (volume two, chapter 20).
how it compares
Two search trees, each putting numbers in, one at a time, counted in comparisons.
| way | n shuffled numbers in | n numbers in order | extra memory | reach for it when |
|---|---|---|---|---|
| a plain search tree | about 10,986 at 1,000, its page's worked average | a path: 499,500 at 1,000 | two links beside each number | numbers arrive shuffled |
| an AVL tree | measured, about 8,723 at 1,000 | 8,977 at 1,000 | two links and its levels beside each number | numbers may arrive in order |