Linked list
how it works
The idea in a few sentences and three pictures, then one run, moment by moment.
A chain of places works like a treasure hunt, each clue telling you where the next one is. Each place holds a number and points at the next place, and a start, holding no number, points at the first. Here the chain is kept in order, smallest first. To put a number in, you walk from the start and stop at the first bigger number. You link the new place in just before it: two pointers change, and no number moves. To take a number out, you walk to it and link its neighbours to each other. The formal name is a singly linked list, and a place is a node. This page counts looks: each place reached, and its number compared. The run after these pictures puts in 23, 7, 42 and 15, takes 7 out, then puts in 31. In its moments, 0 is the start, and each letter names a place in the order it was made.
step 8 of 12
9 is not bigger than 26, so walk on past it.
looks so far: 1
step 9 of 12
14 is not bigger than 26, so walk on past it.
looks so far: 2
step 10 of 12
31 is bigger than 26, so 26 goes just before it.
looks so far: 3
step 11 of 12
Link 26 in just before 31, and point it at 31.
looks so far: 3
- the start, holding no number
- a look, numbered in turn
- looked at now
- looked at, and walked past
- just linked in, with its new pointers
step 8 of 11
12 is smaller than 30, so walk on past it.
looks so far: 1
step 9 of 11
Here is 30.
looks so far: 2
step 10 of 11
Link the places either side of 30 to each other, so nothing points at 30 any more. It is out.
looks so far: 2
- the start, holding no number
- a look, numbered in turn
- looked at now
- looked at, and walked past
- taken out, so nothing points at it
| job | in a chain | in a row |
|---|---|---|
| put 26 in, standing at 14 | point 14 at 26, and 26 at 31: 2 pointers change | move 31 one slot along, then write 26 |
| reach the third number | follow 3 pointers from the start | the row starts at address 2, so slot 3 is at address 4: 1 read |
step 2 of 17
Link 23 in at the start of the chain.
what it remembers to know where it is
- doing operation
- 1
- looking at
- not yet
- in the chain
- 1
Where it says not yet, nothing is held there at that moment.
step 4 of 17
Link 7 in at the start of the chain.
what it remembers to know where it is
- doing operation
- 2
- looking at
- not yet
- in the chain
- 2
Where it says not yet, nothing is held there at that moment.
step 7 of 17
Link 42 in at the end of the chain.
what it remembers to know where it is
- doing operation
- 3
- looking at
- not yet
- in the chain
- 3
Where it says not yet, nothing is held there at that moment.
step 9 of 17
23 is bigger than 15, so 15 goes just before it.
what it remembers to know where it is
- doing operation
- 4
- looking at
- 23
- in the chain
- 3
step 10 of 17
Link 15 in just before 23, and point it at 23.
what it remembers to know where it is
- doing operation
- 4
- looking at
- not yet
- in the chain
- 4
Where it says not yet, nothing is held there at that moment.
step 11 of 17
Here is 7.
what it remembers to know where it is
- doing operation
- 5
- looking at
- 7
- in the chain
- 4
step 12 of 17
Link the places either side of 7 to each other, so nothing points at 7 any more. It is out.
what it remembers to know where it is
- doing operation
- 5
- looking at
- not yet
- in the chain
- 3
Where it says not yet, nothing is held there at that moment.
step 16 of 17
Link 31 in just before 42, and point it at 42.
what it remembers to know where it is
- doing operation
- 6
- looking at
- not yet
- in the chain
- 4
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 chainPython line 16
- walk from the start, one place at a timePython lines 18, 21 and 30
- to put a number in, stop at the first bigger numberPython lines 19 and 20
- and link the new place in just before itPython line 22
- to take a number out, stop at that numberPython line 25
- and link its neighbours to each otherPython line 26
- a number not met before a bigger one is not in the chainPython lines 28 and 29
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 chain: a number, and the place after it."""
def __init__(self, value, after):
self.value = value # the number it holds
self.after = after # the next place, or None at the end
def linked_list(operations):
"""Run a list of operations on a chain of places kept in order.
Each operation is a pair: ('put', n) puts n in, and ('take', n) takes n
out. Returns the chain's numbers, from the start. Each look compares
the number at one place with n.
"""
start = Place(None, None) # an empty chain: a start, pointing at nothing
for action, number in operations:
before, place = start, start.after # walk from the start
if action == 'put':
while place is not None and not place.value > number:
before, place = place, place.after # not bigger: walk on
before.after = Place(number, place) # link it in just before
else:
while place is not None:
if place.value == number: # here it is
before.after = place.after # link its neighbours
break
if place.value > number: # bigger: it is not in the chain
break
before, place = place, place.after # smaller: walk on
numbers = [] # read the chain from the start
place = start.after
while place is not None:
numbers.append(place.value)
place = place.after
return numbers
how it scales
How the looks grow, from ten numbers to ten thousand, each put into an empty chain one at a time. The plot and tables call a look a link followed, as the watch page does.
Each step across or up is ten times the one before, a log-log plot. Biggest first climbs one step up for each step across: ten times the numbers, ten times the looks. Smallest first and shuffled climb two steps: about a hundred times the looks. Smallest first costs 45 looks at 10 numbers, and 49,995,000 at 10,000.
links followed, ten times more at each mark up
, how many numbers are in the chain, ten times more at each mark to the right
- put in smallest first, 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
- shuffled, every order as likelysolid where measured by running it; dashed where its formula carries it on to ten million
- put in biggest first, down to 1solid where measured by running it; dashed where its formula carries it on to ten million
| links followed | 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 links followed 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 linked list's looks yourself, as the plot on this page does.
Run it with Python 3.12 or later. For each size n it puts n numbers into an
empty chain, one at a time, and prints the looks for n down to 1 (biggest
first, the cheapest), for 1 to n (smallest first, the dearest), and the
average over 20 shuffles of 1 to n. A look is one place's number compared
with the number put in. The counts are the same on any computer; only the
time differs.
"""
import random
class Counted:
"""A number that counts the looks made with it: one a place reached.
A take asks one place two questions, is it the number, then is it
bigger: that is still one look.
"""
looks = 0
asked = None # the place's number just asked whether it is the number
def __init__(self, value):
self.value = value
def __eq__(self, other):
Counted.looks += 1
Counted.asked = self
return self.value == other.value
def __gt__(self, other):
if Counted.asked is not self: # a new place: a new look
Counted.looks += 1
Counted.asked = None
return self.value > other.value
class Place:
"""One place of the chain: a number, and the place after it."""
def __init__(self, value, after):
self.value = value # the number it holds
self.after = after # the next place, or None at the end
def linked_list(operations):
"""Run a list of operations on a chain of places kept in order.
Each operation is a pair: ('put', n) puts n in, and ('take', n) takes n
out. Returns the chain's numbers, from the start. Each look compares
the number at one place with n.
"""
start = Place(None, None) # an empty chain: a start, pointing at nothing
for action, number in operations:
before, place = start, start.after # walk from the start
if action == 'put':
while place is not None and not place.value > number:
before, place = place, place.after # not bigger: walk on
before.after = Place(number, place) # link it in just before
else:
while place is not None:
if place.value == number: # here it is
before.after = place.after # link its neighbours
break
if place.value > number: # bigger: it is not in the chain
break
before, place = place, place.after # smaller: walk on
numbers = [] # read the chain from the start
place = start.after
while place is not None:
numbers.append(place.value)
place = place.after
return numbers
def cheapest(n):
"""n down to 1 put in: each new number is the smallest so far."""
return [('put', number) for number in range(n, 0, -1)]
def count(operations):
"""How many looks the chain makes on this list of operations."""
Counted.looks = 0
linked_list([(action, Counted(number)) for action, number in operations])
return Counted.looks
if __name__ == "__main__":
random.seed(1)
print(f"{'n':>6} {'biggest first':>14} {'smallest first':>15} {'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]))
dearest = [('put', number) for number in range(1, n + 1)]
print(f"{n:>6} {count(cheapest(n)):>14} {count(dearest):>15} {sum(shuffles) / 20:>10.1f}")
best, worst and average
One put costs from 0 looks, when it finds the chain empty, to a look at every place, so the order the numbers come in decides the cost.
A case is one kind of input, the thing the method is given, such as numbers put in smallest first, 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.
| bestput in biggest first, down to 1 | averageshuffled, every order as likely | worstput in smallest first, 1 to | |
|---|---|---|---|
| links followed | , one look a put after the first | , about half the dearest for large | , every place each time |
| how the links followed grow in each case | |||
| tight, | |||
| ceiling, | |||
| floor, | |||
extra memory: a pointer beside each number, and the start
Extra memory is the room it needs on top of the input itself, while it runs.
| order put in | looks by each put | looks in all |
|---|---|---|
| 47, 35, 24, 11 | 0, 1, 1, 1 | 3 |
| 24, 47, 11, 35 | 0, 1, 1, 3 | 5 |
| 11, 24, 35, 47 | 0, 1, 2, 3 | 6 |
| 24, 24, 24, 24 | 0, 1, 2, 3 | 6 |
- smallest first,
- shuffled, on average,
- biggest 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. In the boxes on expected cost, a place is a turn in an order, not a chain's place.
the move: price one put
the line:step 8 of 12
3 is not bigger than 40, so walk on past it.
looks so far: 1
step 9 of 12
16 is not bigger than 40, so walk on past it.
looks so far: 2
step 10 of 12
29 is not bigger than 40, so walk on past it.
looks so far: 3
step 11 of 12
Link 40 in at the end of the chain.
looks so far: 3
- the start, holding no number
- a look, numbered in turn
- looked at now
- looked at, and walked past
- just linked in, with its new pointers
Operation 4 puts 40 in, after 3, 16 and 29 went in, smallest first. 40 is bigger than all three, so the walk passes them and links 40 at the end. 3 looks. why it is allowed: Here is how many numbers the chain holds. The walk looks at each place once, from the start, and stops at the first bigger number or at the end.
the move: smallest first, every place
the line:why it is allowed: Each new number is bigger than all before it, so no place stops the walk: the th put passes all numbers. Four 24s cost the same, 0 + 1 + 2 + 3, as no 24 stops the walk. For 4, the fourth put makes 3.
guess it, thenthe move: no order costs more
the line:why it is allowed: The th put meets the numbers already in, so by line 1 it makes at most looks. So no order costs more than line 2's.
guess it, thenthe move: add the puts
the line:why it is allowed: is the looks of numbers put in smallest first. By line 2, puts 1 to make 0, 1, and on up to . For 4, 0 + 1 + 2 + 3 is 6.
guess it, thenthe move: leave out the 0
the line:why it is allowed: Line 4 without its 0, as adding 0 changes nothing.
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 . For 4, 1 + 2 + 3 is 3 times 4, halved, which is 6.
guess it, thenthe move: tidy
the line:why it is allowed: In line 6, is . For 5, 4 times 5, halved, is 10.
guess it, thenthe move: a ceiling
the line:why it is allowed: In line 7, is less than , so is at most times . For 5, 10 is at most 12.5.
guess it, thenthe move: read it as a bound
the line:why it is allowed: By line 8, with the fixed multiple one half.
guess it, thenthe move: a fact about n
the line:why it is allowed: Taking 1 from takes at most half of it once is 2 or more. For 5, 4 is at least 2.5.
guess it, thenthe move: a floor
the line:why it is allowed: In line 7, put line 10's half of for , which is no bigger. Half of times , halved, is a quarter of . For 5, 10 is at least 6.25.
guess it, thenthe move: read it as a bound
the line:why it is allowed: By line 11, from 2 numbers on.
guess it, thenthe move: ceiling and floor together
the line:why it is allowed: Lines 9 and 12 bound by the same growth, .
guess it, then
try it with a small : at , line 4 gives , which you can work out by hand
the move: biggest first, one look each
the line:step 7 of 9
16 is bigger than 3, so 3 goes just before it.
looks so far: 1
step 8 of 9
Link 3 in at the start of the chain.
looks so far: 1
- the start, holding no number
- a look, numbered in turn
- looked at now
- just linked in, with its new pointers
Operation 4 puts 3 in, after 40, 29 and 16 went in, biggest first. 16 is bigger than 3, so the first look stops the walk, and 3 goes in at the start. 1 look. why it is allowed: Each new number is smaller than all before it, so the first place already holds a bigger number. The walk stops there, and the new place is linked in at the start.
the move: no order costs less
the line:why it is allowed: The chain then holds a number, so the walk looks at the first place before it can stop. The first put finds the chain empty and makes none.
guess it, thenthe move: count the looks
the line:why it is allowed: is the looks of numbers put in biggest first. By line 1, puts 2 to make 1 each, and by line 2 no order makes fewer. For 4, 3.
guess it, thenthe move: a ceiling
the line:why it is allowed: Line 3 takes 1 from . For 4, 3 is at most 4.
guess it, thenthe move: read it as a bound
the line:why it is allowed: By line 4.
guess it, thenthe move: a fact about n
the line:why it is allowed: Half of is at least 1 once is 2 or more. For 4, 1 is at most 2.
guess it, thenthe move: a floor
the line:why it is allowed: Line 3 takes away 1, at most line 6's half of , so at least half of is left. For 4, 3 is at least 2.
guess it, thenthe move: read it as a bound
the line:why it is allowed: By line 7, from 2 numbers on.
guess it, thenthe move: ceiling and floor together
the line:why it is allowed: Lines 5 and 8 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 one put by what it passes
the line:step 8 of 11
8 is not bigger than 14, so walk on past it.
looks so far: 1
step 9 of 11
20 is bigger than 14, so 14 goes just before it.
looks so far: 2
step 10 of 11
Link 14 in just before 20, and point it at 20.
looks so far: 2
- the start, holding no number
- a look, numbered in turn
- looked at now
- looked at, and walked past
- just linked in, with its new pointers
Operation 4 puts 14 in, after 20, 8 and 33 went in. It passes 8, the one smaller number, then looks at 20 and stops. 1 + 1 is 2 looks. why it is allowed: The numbers are all different. The walk passes every smaller number, then stops at the first bigger one. A new best, bigger than all before it, finds none to stop at.
the move: add over the puts
the line:put smaller numbers passed plus 1 less 1 for a new best looks 2 0 1 1 0 3 1 1 1 1 1 0 1 0 1 in all 1 3 2 2 Putting in 2, 3, then 1. Each put's looks are the smaller numbers it passes, plus 1, less 1 for a new best. why it is allowed: Line 1, added over the puts. Each smaller number a put passes makes one pair in order, the smaller put in first. On 2, 3, 1: 1 pair in order, plus 3, less 2 new bests, is 2.
guess it, thenthe move: average piece by piece
the line:order put in pairs in order new bests looks 1, 2, 3 3 3 3 1, 3, 2 2 2 3 2, 1, 3 2 2 3 2, 3, 1 1 2 2 3, 1, 2 1 1 3 3, 2, 1 0 1 2 in all 9 11 16 Each order of 1, 2 and 3. Its looks are its pairs in order, plus 3, less its new bests. In all, 9 + 18 less 11 is 16, and the 18 is 3 for each of the 6 orders. why it is allowed: is the looks averaged over every order of different numbers. By line 2, each order's looks are its pairs in order, plus , less its new bests. Averages add piece by piece: add each piece over every order, then divide by how many orders there are. For 3, 9 over 6 + 3 less 11 over 6, which is 16 over 6.
guess it, thenthe move: use the page on expected cost
the line:where does this come from?
question 2 of the page expected costShuffle different numbers at random. How many pairs stand out of order, on average? the move: out of order half the time
the line:Trading places 1 and 3 pairs each shuffle holding them in order with one holding them out of order, 3 and 3. shuffle places 1 and 2 places 1 and 3 places 2 and 3 pairs out of order 1, 2, 3 0 1, 3, 2 yes 1 2, 1, 3 yes 1 2, 3, 1 yes yes 2 3, 1, 2 yes yes 2 3, 2, 1 yes yes yes 3 in all 3 3 3 9 Each shuffle of 1, 2 and 3, a yes where a pair of places is out of order. 9 over 6 is 1.5. why it is allowed: A pair is two places. Trading their numbers pairs each shuffle with another, and trading back undoes it. Each two has the pair out of order in exactly one, and both are as likely: chance one half.
the move: expected counts add
the line:why it is allowed: The table at line 1 adds two ways: down its last column, 9, and along its bottom row, 3 + 3 + 3. Over 6 shuffles, 9 over 6 is the average count, 1.5, and 3 over 6 three times is the pairs' chances added, 1.5 too. Both add the same yeses, so they agree for any , though the pairs depend on each other. With unequal chances, weight each yes by its order's chance. 2, 1, 3 at 3 over 4 and 1, 2, 3 at 1 over 4 give 3 over 4 both ways.
the move: one half for each pair
the line:why it is allowed: By line 2 the expected count adds line 1's one half once per pair.
the move: count the pairs
the line:why it is allowed: Let be the expected count, by line 3 half the number of pairs. The first place pairs with the after it, the next with one fewer, down to 1. For 3 places, 2 + 1 is 3 pairs, so 1.5.
the move: add them the other way round
the line:why it is allowed: The same numbers in the other order.
the 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 page on adding up 1 to adds the numbers from 1 to any whole number. They add up to that number times one more than it, halved: 1 + 2 + 3 is 3 times 4, halved, which is 6. In its working, its sum runs from 1 up to its own last number, which it calls . Here that is .
the move: tidy the bracket
the line:why it is allowed: is .
the move: multiply the halves
the line:why it is allowed: Half of a half is a quarter. For 3, 2 times 3 over 4 is 1.5.
the move: read it
the line:why it is allowed: By lines 4 to 7 there are pairs, and line 8 is half that. For 3, 1.5, as line 1 counted.
why it is allowed: There are 1 + 2 + ... + pairs, each in order in half the orders. Line 3's table holds 9 in order over the 6 orders, and the box's table 9 out of order. So both average the same, , which the box works out. For 3, 9 over 6 is 1.5.
guess it, thenthe move: use the page on expected cost again
the line:where does this come from?
question 3 of the page expected costWalk along different numbers shuffled at random. How many new bests turn up, on average? the move: a new best at place k
the line:Trading place 3 with place 1 or 2 moves the 3 there, and trading back undoes it. 2 shuffles hold the 3 at each place. shuffle place 1 place 2 place 3 new bests 1, 2, 3 yes yes yes 3 1, 3, 2 yes yes 2 2, 1, 3 yes yes 2 2, 3, 1 yes yes 2 3, 1, 2 yes 1 3, 2, 1 yes 1 in all 6 3 2 11 Each shuffle of 1, 2 and 3, a yes where a place holds a new best. 11 over 6 is 1 + 1 over 2 + 1 over 3. why it is allowed: The number at place is a new best when it is the biggest of the first . Trade place with another of the first : a biggest at one moves to the other, and trading back undoes it. So it stands equally often at each of the first places: at place in 1 of every shuffles. For 3, the 3 stands at each place in 2 of 6.
the move: add the chances
the line:why it is allowed: Let be the expected new bests. Each place is a piece, a new best or not. By line 2 of question 2 of the page expected cost, adds their chances: 1 over for place , by line 1.
the move: read it
the line:why it is allowed: By line 2, the harmonic sum. For 3, 11 over 6, about 1.83, as line 1 counted.
why it is allowed: The th put is a new best with chance 1 over , and the chances add: the box under this line shows both. For 3, 1 + 1 over 2 + 1 over 3 is 11 over 6, line 3's.
guess it, thenthe move: name the harmonic sum
the line:why it is allowed: Line 5's bracket is the harmonic sum, . For 3, about 1.83, so is about 2.67, line 3's 16 over 6.
guess it, thenthe move: a ceiling from the dearest order
the line:why it is allowed: No order costs more than smallest first, by the smallest-first question's line 3 and its line 7. So neither does the average. For 3, 2.67 is at most 3.
guess it, thenthe move: a simpler ceiling
the line:why it is allowed: As in the smallest-first question's line 8, is at most times . For 3, 2.67 is at most 4.5.
guess it, thenthe move: read it as a bound
the line:why it is allowed: By line 8.
guess it, thenthe move: a floor
the line:why it is allowed: adds numbers, each at most 1, so in line 6 less is at least 0. For 3, 2.67 is at least 1.5.
guess it, thenthe move: a simpler floor
the line:why it is allowed: In line 10, put half of for , which is no bigger by the smallest-first question's line 10. For 4, line 10's 3 is at least 2.
guess it, thenthe move: read it as a bound
the line:why it is allowed: By line 11, from 2 numbers on.
guess it, thenthe move: ceiling and floor together
the line:why it is allowed: Lines 9 and 12 bound by the same growth, . At 1,000 numbers, is about 7.5, beside about 250,000 pairs in order on average, of 499,500 pairs.
guess it, then
try it on small inputs: over every order of 3 numbers put in, the average is about 2.67
the move: the same comparisons
the line:put row before compared with moved along row after 14 empty none none 14 6 14 14 14 6, 14 25 6, 14 6, 14 none 6, 14, 25 9 6, 14, 25 6, 14 25, 14 6, 9, 14, 25 Four puts into a row kept in order. 5 comparisons, as a chain makes 5 looks, and 3 moves, which a chain never makes. why it is allowed: It scans from the front and stops at the first bigger number, as the chain's walk does. So its comparisons are the chain's looks, on average.
the move: a put moves the bigger numbers
the line:the row slot 1 slot 2 slot 3 slot 4 before 6 14 25 25 moved 6 14 25 14 moved 6 14 25 9 written 6 9 14 25 The fourth put above, 9 into 6, 14, 25. 25 moves one slot along first, then 14, then 9 is written in the gap, the empty cell. why it is allowed: The new number needs the slot the scan stopped at, so every bigger number shifts one slot along. The back moves first: moving 14 first would cover 25.
guess it, thenthe move: a move is a pair out of order
the line:why it is allowed: By line 2, a put moves exactly the bigger numbers already in. 14, 6, 25, 9 holds 3 such pairs, 14 and 6, 14 and 9, 25 and 9, and makes 3 moves.
guess it, thenthe move: average them
the line:why it is allowed: is the moves averaged over every order of different numbers. By line 3, each order's moves are its pairs out of order. For 3, the 6 orders hold 9 in all, so is 9 over 6, 1.5.
guess it, thenthe move: use the page on expected cost
the line:where does this come from?
question 2 of the page expected costShuffle different numbers at random. How many pairs stand out of order, on average? the move: out of order half the time
the line:Trading places 1 and 3 pairs each shuffle holding them in order with one holding them out of order, 3 and 3. shuffle places 1 and 2 places 1 and 3 places 2 and 3 pairs out of order 1, 2, 3 0 1, 3, 2 yes 1 2, 1, 3 yes 1 2, 3, 1 yes yes 2 3, 1, 2 yes yes 2 3, 2, 1 yes yes yes 3 in all 3 3 3 9 Each shuffle of 1, 2 and 3, a yes where a pair of places is out of order. 9 over 6 is 1.5. why it is allowed: A pair is two places. Trading their numbers pairs each shuffle with another, and trading back undoes it. Each two has the pair out of order in exactly one, and both are as likely: chance one half.
the move: expected counts add
the line:why it is allowed: The table at line 1 adds two ways: down its last column, 9, and along its bottom row, 3 + 3 + 3. Over 6 shuffles, 9 over 6 is the average count, 1.5, and 3 over 6 three times is the pairs' chances added, 1.5 too. Both add the same yeses, so they agree for any , though the pairs depend on each other. With unequal chances, weight each yes by its order's chance. 2, 1, 3 at 3 over 4 and 1, 2, 3 at 1 over 4 give 3 over 4 both ways.
the move: one half for each pair
the line:why it is allowed: By line 2 the expected count adds line 1's one half once per pair.
the move: count the pairs
the line:why it is allowed: Let be the expected count, by line 3 half the number of pairs. The first place pairs with the after it, the next with one fewer, down to 1. For 3 places, 2 + 1 is 3 pairs, so 1.5.
the move: add them the other way round
the line:why it is allowed: The same numbers in the other order.
the 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 page on adding up 1 to adds the numbers from 1 to any whole number. They add up to that number times one more than it, halved: 1 + 2 + 3 is 3 times 4, halved, which is 6. In its working, its sum runs from 1 up to its own last number, which it calls . Here that is .
the move: tidy the bracket
the line:why it is allowed: is .
the move: multiply the halves
the line:why it is allowed: Half of a half is a quarter. For 3, 2 times 3 over 4 is 1.5.
the move: read it
the line:why it is allowed: By lines 4 to 7 there are pairs, and line 8 is half that. For 3, 1.5, as line 1 counted.
why it is allowed: There are 1 + 2 + ... + pairs, each out of order in half the orders, and expected counts add. The box under this line shows both, at its lines 1 and 2, then adds the pairs. For 3, 2 times 3 over 4 is 1.5, line 4's.
guess it, thenthe move: add the comparisons
the line:numbers the row's moves, the chain's looks, the row's comparisons and moves row over chain 10 22.5 about 29.6 about 52.1 about 1.76 100 2,475 about 2,569.8 about 5,044.8 about 1.96 1,000 249,750 about 250,742.5 about 500,492.5 about 2.00 Each on average over every order, from line 5, the shuffled question's line 6 and line 7 below. why it is allowed: By line 1, the comparisons are , the shuffled question's line 6. Add to both sides of line 5. The moves nearly match the looks, so from about 100 numbers on the row's comparisons and moves are about twice the chain's looks, as the table shows.
guess it, thenthe move: two quarters make a half
the line:why it is allowed: In line 6, a quarter and a quarter of make a half. For 4, 6 + 4 less about 2.08, about 7.92. Section 7 sets this count beside the books' clock.
guess it, thenthe move: the moves are at most the looks
the line:why it is allowed: For 4, the moves' 3 is at most 's 4.92, so 7.92 is at most 9.83. Line 5's moves are always at most , which adds less , at least 0 by the shuffled question's line 10. So write for them in line 6, whose rest is again, by the shuffled question's line 6.
guess it, thenthe move: a ceiling from the chain's
the line:why it is allowed: By the shuffled question's line 8, each is at most half of . For 4, 9.83 is at most 16.
guess it, thenthe move: read it as a bound
the line:why it is allowed: By line 9.
guess it, thenthe move: the looks alone
the line:why it is allowed: In line 6, the moves' is at least 0, so leave it out. The rest is , by the shuffled question's line 6. For 4, 7.92 is at least 4.92.
guess it, thenthe move: a floor from the chain's
the line:why it is allowed: By the shuffled question's line 11, is at least an eighth of from 2 numbers on. For 4, 4.92 is at least 2.
guess it, thenthe move: read it as a bound
the line:why it is allowed: By line 12, from 2 numbers on.
guess it, thenthe move: ceiling and floor together
the line:why it is allowed: Lines 10 and 13 bound the comparisons and moves by the same growth, .
guess it, then
try it with a small : at , line 4 gives , which you can work out by hand
count it yourself
Count every look as 5, 12, 20, 33 and 41 go into an empty chain, smallest first.
| step | the chain | what happens | links followed |
|---|---|---|---|
| 1 | Start with an empty chain, and 5 operations to do. | 0 | |
| 2 | 5 | Link 5 in at the start of the chain.5 | 0 |
| 3 | 5 | 5 is not bigger than 12, so walk on past it.5 | 1 |
| 4 | 5, 12 | Link 12 in at the end of the chain.5, 12 | 1 |
| 5 | 5, 12 | 5 is not bigger than 20, so walk on past it.5, 12 | 2 |
| 6 | 5, 12 | 12 is not bigger than 20, so walk on past it.5, 12 | 3 |
| 7 | 5, 12, 20 | Link 20 in at the end of the chain.5, 12, 20 | 3 |
| 8 | 5, 12, 20 | 5 is not bigger than 33, so walk on past it.5, 12, 20 | 4 |
| 9 | 5, 12, 20 | 12 is not bigger than 33, so walk on past it.5, 12, 20 | 5 |
| 10 | 5, 12, 20 | 20 is not bigger than 33, so walk on past it.5, 12, 20 | 6 |
| 11 | 5, 12, 20, 33 | Link 33 in at the end of the chain.5, 12, 20, 33 | 6 |
| 12 | 5, 12, 20, 33 | 5 is not bigger than 41, so walk on past it.5, 12, 20, 33 | 7 |
| 13 | 5, 12, 20, 33 | 12 is not bigger than 41, so walk on past it.5, 12, 20, 33 | 8 |
| 14 | 5, 12, 20, 33 | 20 is not bigger than 41, so walk on past it.5, 12, 20, 33 | 9 |
| 15 | 5, 12, 20, 33 | 33 is not bigger than 41, so walk on past it.5, 12, 20, 33 | 10 |
| 16 | 5, 12, 20, 33, 41 | Link 41 in at the end of the chain.5, 12, 20, 33, 41 | 10 |
| 17 | 5, 12, 20, 33, 41 | Done. The chain holds 5 numbers.5, 12, 20, 33, 41 | 10 |
In all, 10 links followed. The formula from section 4, , gives at : the same.
where you meet it
Most programs keep numbers in a row, as Python's list does; chains do a few jobs inside big programs.
the Linux kernel's lists
The Linux kernel, the core of the operating system, ties its records, each a bundle of data kept together, into doubly linked chains with list_head. Each record holds two pointers, one to the next place and one to the place before. A record holding two sets of these pointers sits in two chains at once.
source: the Linux kernel's include/linux/types.h, struct list_head, and include/linux/list.h, list_add and list_del
Python's OrderedDict
Python's OrderedDict keeps its keys, the names its values are filed under, in the order they went in. Python's source holds it twice, in C and in Python. The one in Python links the keys both ways in a ring round one place holding no key, like this page's start. Moving a key to the end relinks its one place. The first table below tries it.
source: CPython's Lib/collections/__init__.py, class OrderedDict, the version written in Python; Python's documentation, collections.OrderedDict (opens in a new tab)
C++'s std::list and splice
C++'s std::list is a chain that can be walked both ways. Its splice moves places into another list: nothing is copied, and a pointer to a moved place still finds it. The second table below splices two.
source: the C++ standard, list.overview (opens in a new tab) and list.ops (opens in a new tab), list::splice
| asked | in plain words | answer | the keys after |
|---|---|---|---|
| list(d) | list the keys | [31, 8, 50] | 31, 8, 50 |
| d.move_to_end(31) | move 31 to the end | None | 8, 50, 31 |
| d.move_to_end(50, last=False) | move 50 to the front | None | 50, 8, 31 |
| d.popitem() | take the last key out | (31, None) | 50, 8 |
| d.popitem(last=False) | take the first key out | (50, None) | 8 |
| chain | before | after |
|---|---|---|
| first | 5, 8, 13 | 5 |
| second | 2, 21 | 2, 8, 13, 21 |
| moment | the row | the pointer to slot 2 finds |
|---|---|---|
| before | 6, 14, 25 | 14 |
| after putting 9 in | 6, 9, 14, 25 | 9, not 14 |
what is used instead
Sebastian Bourges' books give the rule: 'Default to the dynamic array' (volume two, chapter 22), a row with room to spare, as Python's list is. They keep a chain for three reasons: runs of places spliced in whole, pointers that must stay good, and records that are large or cannot move.
how it compares
Two ways to keep numbers in order, side by side. Each puts shuffled numbers in, one at a time.
| way | find the place | put it in | n shuffled numbers in, on average | extra memory | reach for it when |
|---|---|---|---|---|---|
| a chain of places | walk from the start | 2 pointers change | looks | a pointer beside each number | you splice runs of places in whole, pointers must stay valid, or records are large or cannot move |
| a row in order | scan from the front, the same comparisons | move each bigger number along | comparisons and moves | spare room, if the row doubles | almost always: the books' default |
| numbers | the chain's work over the row's | the chain's time over the row's |
|---|---|---|
| 1,000 | 0.50 | 1.9 |
| 4,000 | 0.49 | 6.8 |
| 8,000 | 0.50 | 7.9 |
| 16,000 | 0.50 | 9.7 |
| 32,000 | 0.50 | 14.5 |
- read in this wait, numbered in turn
- not read yet
- read in an earlier wait
- other memory
- a pointer read, giving the next address
- read at once, every address known ahead