Skip to content

Linked list

storing

Level 1 of 3

Also called Sorted singly 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.

  1. step 8 of 12

    911431

    9 is not bigger than 26, so walk on past it.

    looks so far: 1

  2. step 9 of 12

    9114231

    14 is not bigger than 26, so walk on past it.

    looks so far: 2

  3. step 10 of 12

    91142313

    31 is bigger than 26, so 26 goes just before it.

    looks so far: 3

  4. step 11 of 12

    9114226313

    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
Operation 4 puts 26 in, after operations 1 to 3 put in 9, 31 and 14. One step a line: the walk passes 9 and 14, stops at 31, the first bigger number, and links 26 in before it. 3 looks, and no number moves.
  1. step 8 of 11

    1213045

    12 is smaller than 30, so walk on past it.

    looks so far: 1

  2. step 9 of 11

    12130245

    Here is 30.

    looks so far: 2

  3. step 10 of 11

    1213045

    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
Operation 4 takes 30 out, after operations 1 to 3 put in 12, 30 and 45. The walk passes 12 and finds 30, and 12's link jumps to 45. 2 looks. Taking 20 instead, the walk would stop at 30, a bigger number: 20 is not in the chain.
jobin a chainin a row
put 26 in, standing at 14point 14 at 26, and 26 at 31: 2 pointers changemove 31 one slot along, then write 26
reach the third numberfollow 3 pointers from the startthe row starts at address 2, so slot 3 is at address 4: 1 read
The same numbers as a chain and as a row. Standing at 14 means you already point at it, so there is no walk. Sebastian Bourges' books set these two jobs side by side (volume two, chapter 22): each way wins one.
Putting in and taking out: 8 moments of its 17 steps, the steps between them left for the watch page
  1. step 2 of 17

    0a23

    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.

    watch from here

  2. step 4 of 17

    0b7a23

    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.

    watch from here

  3. step 7 of 17

    0b7a23c42

    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.

    watch from here

  4. step 9 of 17

    0b7a23c42

    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

    watch from here

  5. step 10 of 17

    0b7d15a23c42

    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.

    watch from here

  6. step 11 of 17

    0b7d15a23c42

    Here is 7.

    what it remembers to know where it is
    doing operation
    5
    looking at
    7
    in the chain
    4

    watch from here

  7. step 12 of 17

    0b7d15a23c42

    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.

    watch from here

  8. step 16 of 17

    0b7d15a23e31c42

    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.

    watch from here

the steps, in plain words
  1. start with an empty chainPython line 16
  2. walk from the start, one place at a timePython lines 18, 21 and 30
  3. to put a number in, stop at the first bigger numberPython lines 19 and 20
  4. and link the new place in just before itPython line 22
  5. to take a number out, stop at that numberPython line 25
  6. and link its neighbours to each otherPython line 26
  7. 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

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

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

  • put in smallest first, 1 to nnsolid where measured by running it; dashed where its formula carries it on to ten millionslope 2: ten times n, 100 times the work
  • shuffled, every order as likelysolid where measured by running it; dashed where its formula carries it on to ten million
  • put in biggest first, nn down to 1solid where measured by running it; dashed where its formula carries it on to ten million
what the dearest order costs, at a billion links followed a second
nnlinks followedtime
1,000499,500about 500 microseconds
100,0004,999,950,000about 5 seconds
10,000,00049,999,995,000,000about 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.

what each case costs, and how fast that cost grows; section 4 works out every formula in it
bestput in biggest first, nn down to 1averageshuffled, every order as likelyworstput in smallest first, 1 to nn
links followedn−1n - 1, one look a put after the first(n−1)n4+n−H(n)\frac{(n - 1)n}{4} + n - H(n), about half the dearest for large nn(n−1)n2\frac{(n - 1)n}{2}, every place each time
how the links followed grow in each case
tight, Θ\ThetaΘ(n)\Theta(n)Θ(n2)\Theta(n^2)Θ(n2)\Theta(n^2)
ceiling, OOO(n)O(n)O(n2)O(n^2)O(n2)O(n^2)
floor, Ω\OmegaΩ(n)\Omega(n)Ω(n2)\Omega(n^2)Ω(n2)\Omega(n^2)

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 inlooks by each putlooks in all
47, 35, 24, 110, 1, 1, 13
24, 47, 11, 350, 1, 1, 35
11, 24, 35, 470, 1, 2, 36
24, 24, 24, 240, 1, 2, 36
Three orders of 11, 24, 35 and 47, then 24 four times. Four 24s cost 6, as smallest first does: an equal number never stops a put.
looksnumbers put in05010015020005101520looksnumbers put in05010015020005101520
  • smallest first, (n−1)n2\frac{(n - 1)n}{2}
  • shuffled, on average, (n−1)n4+n−H(n)\frac{(n - 1)n}{4} + n - H(n)
  • biggest first, n−1n - 1
Double the numbers and smallest first makes about four times the looks, shuffled a little less. Biggest first only doubles.

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.

Why do nn numbers put in smallest first cost (n−1)n2\frac{(n - 1)n}{2} looks, the most any order can?
  1. the move: price one put

    the line:
    a put into a chainof m numbers makesat most m looks\begin{gathered} \text{a put into a chain} \\ \text{of } m \text{ numbers makes} \\ \text{at most } m \text{ looks} \end{gathered}
    1. step 8 of 12

      311629

      3 is not bigger than 40, so walk on past it.

      looks so far: 1

    2. step 9 of 12

      3116229

      16 is not bigger than 40, so walk on past it.

      looks so far: 2

    3. step 10 of 12

      31162293

      29 is not bigger than 40, so walk on past it.

      looks so far: 3

    4. step 11 of 12

      3116229340

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

  2. the move: smallest first, every place

    the line:
    smallest first, the kth putmakes k−1 looks\begin{gathered} \text{smallest first, the } k\text{th put} \\ \text{makes } k - 1 \text{ looks} \end{gathered}

    why it is allowed: Each new number is bigger than all before it, so no place stops the walk: the kkth put passes all k−1k - 1 numbers. Four 24s cost the same, 0 + 1 + 2 + 3, as no 24 stops the walk. For 4, the fourth put makes 3.

  3. the move: no order costs more

    the line:
    in any order, the kthput makes at mostk−1 looks\begin{gathered} \text{in any order, the } k\text{th} \\ \text{put makes at most} \\ k - 1 \text{ looks} \end{gathered}

    why it is allowed: The kkth put meets the k−1k - 1 numbers already in, so by line 1 it makes at most k−1k - 1 looks. So no order costs more than line 2's.

  4. the move: add the puts

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

    why it is allowed: WW is the looks of nn numbers put in smallest first. By line 2, puts 1 to nn make 0, 1, and on up to n−1n - 1. For 4, 0 + 1 + 2 + 3 is 6.

  5. the move: leave out the 0

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

    why it is allowed: Line 4 without its 0, as adding 0 changes nothing.

  6. the move: use the page on adding up

    the line:
    W=(n−1)((n−1)+1)2W = \frac{(n - 1)\bigl((n - 1) + 1\bigr)}{2}
    where does this come from?
    question 1 of the page adding up 1+2+⋯+n1 + 2 + \dots + nFit two staircases of squares together. What shape do they make?
    1. the move: draw the sum as a staircase

      the line:
      S=1+2+⋯+nS = 1 + 2 + \dots + n

      why it is allowed: Let SS be the sum of the whole numbers from 1 to nn. Draw it as a staircase, a column for each number: 1 square, then 2, and so on up to nn. For 5, columns of 1, 2, 3, 4 and 5 hold 15 squares.

    2. the move: take two staircases

      the line:
      2S=2(1+2+⋯+n)2S = 2(1 + 2 + \dots + n)

      why it is allowed: Two staircases hold twice the squares. Doubling both sides of line 1 keeps it true.

    3. the move: fit them into a rectangle

      the line:
      2S=n(n+1)2S = n(n + 1)
      Blue stands, yellow hangs. Two staircases of 1 to 5 squares fill a rectangle 5 wide and 6 tall, 30 squares. So 1 + 2 + 3 + 4 + 5 is 5 times 6, halved, which is 15.

      why it is allowed: Stand one staircase with its tallest column on the left. Hang the other upside down from the top, its tallest column on the right, as in the picture. The first column holds nn standing and 1 hanging. Each column to the right, the standing one loses a square and the hanging one gains one. So every column holds n+1n + 1, and the nn columns fill a rectangle nn wide and n+1n + 1 tall.

    4. the move: halve both sides

      the line:
      S=n(n+1)2S = \frac{n(n + 1)}{2}

      why it is allowed: Halving both sides of line 3 keeps it true and leaves one SS. For 5, half of 30 is 15.

    the whole page: adding up 1+2+⋯+n1 + 2 + \dots + n

    why it is allowed: The box under this line shows that 1 up to a last number adds to that number times one more, halved. Here the last number is n−1n - 1. For 4, 1 + 2 + 3 is 3 times 4, halved, which is 6.

  7. the move: tidy

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

    why it is allowed: In line 6, (n−1)+1(n - 1) + 1 is nn. For 5, 4 times 5, halved, is 10.

  8. the move: a ceiling

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

    why it is allowed: In line 7, n−1n - 1 is less than nn, so (n−1)n(n - 1)n is at most nn times nn. For 5, 10 is at most 12.5.

  9. the move: read it as a bound

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

    why it is allowed: By line 8, with the fixed multiple one half.

  10. the move: a fact about n

    the line:
    n−1≥n2 for n≥2n - 1 \ge \frac{n}{2} \text{ for } n \ge 2

    why it is allowed: Taking 1 from nn takes at most half of it once nn is 2 or more. For 5, 4 is at least 2.5.

  11. the move: a floor

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

    why it is allowed: In line 7, put line 10's half of nn for n−1n - 1, which is no bigger. Half of nn times nn, halved, is a quarter of n2n^2. For 5, 10 is at least 6.25.

  12. the move: read it as a bound

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

    why it is allowed: By line 11, from 2 numbers on.

  13. the move: ceiling and floor together

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

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

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

Why do nn numbers put in biggest first cost only n−1n - 1 looks, the fewest any order can?
  1. the move: biggest first, one look each

    the line:
    biggest first, each put afterthe first makes 1 look\begin{gathered} \text{biggest first, each put after} \\ \text{the first makes 1 look} \end{gathered}
    1. step 7 of 9

      1612940

      16 is bigger than 3, so 3 goes just before it.

      looks so far: 1

    2. step 8 of 9

      31612940

      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.

  2. the move: no order costs less

    the line:
    every put after the firstmakes at least 1 look\begin{gathered} \text{every put after the first} \\ \text{makes at least 1 look} \end{gathered}

    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.

  3. the move: count the looks

    the line:
    B=n−1B = n - 1

    why it is allowed: BB is the looks of nn numbers put in biggest first. By line 1, puts 2 to nn make 1 each, and by line 2 no order makes fewer. For 4, 3.

  4. the move: a ceiling

    the line:
    B≤nB \le n

    why it is allowed: Line 3 takes 1 from nn. For 4, 3 is at most 4.

  5. the move: read it as a bound

    the line:
    B∈O(n)B \in O(n)

    why it is allowed: By line 4.

  6. the move: a fact about n

    the line:
    1≤n2 for n≥21 \le \frac{n}{2} \text{ for } n \ge 2

    why it is allowed: Half of nn is at least 1 once nn is 2 or more. For 4, 1 is at most 2.

  7. the move: a floor

    the line:
    B≥n2 for n≥2B \ge \frac{n}{2} \text{ for } n \ge 2

    why it is allowed: Line 3 takes away 1, at most line 6's half of nn, so at least half of nn is left. For 4, 3 is at least 2.

  8. the move: read it as a bound

    the line:
    B∈Ω(n)B \in \Omega(n)

    why it is allowed: By line 7, from 2 numbers on.

  9. the move: ceiling and floor together

    the line:
    B∈Θ(n)B \in \Theta(n)

    why it is allowed: Lines 5 and 8 bound BB by the same growth, nn.

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

Why do shuffled numbers cost (n−1)n4+n−H(n)\frac{(n - 1)n}{4} + n - H(n) looks on average?
  1. the move: price one put by what it passes

    the line:
    a put makes 1 lookfor each smaller numberalready in, and 1 moreunless it is a new best\begin{gathered} \text{a put makes 1 look} \\ \text{for each smaller number} \\ \text{already in, and 1 more} \\ \text{unless it is a new best} \end{gathered}
    1. step 8 of 11

      812033

      8 is not bigger than 14, so walk on past it.

      looks so far: 1

    2. step 9 of 11

      8120233

      20 is bigger than 14, so 14 goes just before it.

      looks so far: 2

    3. step 10 of 11

      811420233

      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.

  2. the move: add over the puts

    the line:
    the looks are thepairs in order, plus n,less the new bests\begin{gathered} \text{the looks are the} \\ \text{pairs in order, plus } n, \\ \text{less the new bests} \end{gathered}
    putsmaller numbers passedplus 1less 1 for a new bestlooks
    20110
    31111
    10101
    in all1322
    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 nn 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.

  3. the move: average piece by piece

    the line:
    A=average pairsin order+n−average new bests\begin{gathered} A = \text{average pairs} \\ \text{in order} + n \\ - \text{average new bests} \end{gathered}
    order put inpairs in ordernew bestslooks
    1, 2, 3333
    1, 3, 2223
    2, 1, 3223
    2, 3, 1122
    3, 1, 2113
    3, 2, 1012
    in all91116
    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: AA is the looks averaged over every order of nn different numbers. By line 2, each order's looks are its pairs in order, plus nn, 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.

  4. the move: use the page on expected cost

    the line:
    A=(n−1)n4+n−average new bests\begin{gathered} A = \frac{(n - 1)n}{4} + n \\ - \text{average new bests} \end{gathered}
    where does this come from?
    question 2 of the page expected costShuffle nn different numbers at random. How many pairs stand out of order, on average?
    1. the move: out of order half the time

      the line:
      a pair stands out of orderwith chance one half\begin{gathered} \text{a pair stands out of order} \\ \text{with chance one half} \end{gathered}
      in order1231322133 shufflesout of order3212313123 shuffles=
      Trading places 1 and 3 pairs each shuffle holding them in order with one holding them out of order, 3 and 3.
      shuffleplaces 1 and 2places 1 and 3places 2 and 3pairs out of order
      1, 2, 30
      1, 3, 2yes1
      2, 1, 3yes1
      2, 3, 1yesyes2
      3, 1, 2yesyes2
      3, 2, 1yesyesyes3
      in all3339
      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.

    2. the move: expected counts add

      the line:
      the expected countadds up the chanceof every pair\begin{gathered} \text{the expected count} \\ \text{adds up the chance} \\ \text{of every pair} \end{gathered}

      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 nn, 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.

    3. the move: one half for each pair

      the line:
      one half timesthe number of pairs\begin{gathered} \text{one half times} \\ \text{the number of pairs} \end{gathered}

      why it is allowed: By line 2 the expected count adds line 1's one half once per pair.

    4. the move: count the pairs

      the line:
      P=12×((n−1)+⋯+1)P = \frac{1}{2} \times \bigl((n - 1) + \dots + 1\bigr)

      why it is allowed: Let PP be the expected count, by line 3 half the number of pairs. The first place pairs with the n−1n - 1 after it, the next with one fewer, down to 1. For 3 places, 2 + 1 is 3 pairs, so 1.5.

    5. the move: add them the other way round

      the line:
      P=12×(1+⋯+(n−1))P = \frac{1}{2} \times \bigl(1 + \dots + (n - 1)\bigr)

      why it is allowed: The same numbers in the other order.

    6. the move: use the page on adding up

      the line:
      P=12×(n−1)((n−1)+1)2P = \frac{1}{2} \times \frac{(n - 1)\bigl((n - 1) + 1\bigr)}{2}
      where does this come from?
      question 1 of the page adding up 1+2+⋯+n1 + 2 + \dots + nFit two staircases of squares together. What shape do they make?
      1. the move: draw the sum as a staircase

        the line:
        S=1+2+⋯+nS = 1 + 2 + \dots + n

        why it is allowed: Let SS be the sum of the whole numbers from 1 to nn. Draw it as a staircase, a column for each number: 1 square, then 2, and so on up to nn. For 5, columns of 1, 2, 3, 4 and 5 hold 15 squares.

      2. the move: take two staircases

        the line:
        2S=2(1+2+⋯+n)2S = 2(1 + 2 + \dots + n)

        why it is allowed: Two staircases hold twice the squares. Doubling both sides of line 1 keeps it true.

      3. the move: fit them into a rectangle

        the line:
        2S=n(n+1)2S = n(n + 1)
        Blue stands, yellow hangs. Two staircases of 1 to 5 squares fill a rectangle 5 wide and 6 tall, 30 squares. So 1 + 2 + 3 + 4 + 5 is 5 times 6, halved, which is 15.

        why it is allowed: Stand one staircase with its tallest column on the left. Hang the other upside down from the top, its tallest column on the right, as in the picture. The first column holds nn standing and 1 hanging. Each column to the right, the standing one loses a square and the hanging one gains one. So every column holds n+1n + 1, and the nn columns fill a rectangle nn wide and n+1n + 1 tall.

      4. the move: halve both sides

        the line:
        S=n(n+1)2S = \frac{n(n + 1)}{2}

        why it is allowed: Halving both sides of line 3 keeps it true and leaves one SS. For 5, half of 30 is 15.

      the whole page: adding up 1+2+⋯+n1 + 2 + \dots + n

      why it is allowed: The page on adding up 1 to nn 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 nn. Here that is n−1n - 1.

    7. the move: tidy the bracket

      the line:
      P=12×(n−1)n2P = \frac{1}{2} \times \frac{(n - 1)n}{2}

      why it is allowed: (n−1)+1(n - 1) + 1 is nn.

    8. the move: multiply the halves

      the line:
      P=(n−1)n4P = \frac{(n - 1)n}{4}

      why it is allowed: Half of a half is a quarter. For 3, 2 times 3 over 4 is 1.5.

    9. the move: read it

      the line:
      half the pairs,on average\begin{gathered} \text{half the pairs,} \\ \text{on average} \end{gathered}

      why it is allowed: By lines 4 to 7 there are (n−1)n2\frac{(n - 1)n}{2} pairs, and line 8 is half that. For 3, 1.5, as line 1 counted.

    the whole page: expected cost

    why it is allowed: There are 1 + 2 + ... + (n−1)(n - 1) 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, (n−1)n4\frac{(n - 1)n}{4}, which the box works out. For 3, 9 over 6 is 1.5.

  5. the move: use the page on expected cost again

    the line:
    A=(n−1)n4+n−(1+12+13+⋯+1n)\begin{gathered} A = \frac{(n - 1)n}{4} + n \\ - \Bigl(1 + \frac{1}{2} + \frac{1}{3} + \dots + \frac{1}{n}\Bigr) \end{gathered}
    where does this come from?
    question 3 of the page expected costWalk along nn different numbers shuffled at random. How many new bests turn up, on average?
    1. the move: a new best at place k

      the line:
      place k holds a new bestwith chance 1 over k\begin{gathered} \text{place } k \text{ holds a new best} \\ \text{with chance 1 over } k \end{gathered}
      3 at place 13213122 shuffles3 at place 31232132 shuffles=3 at place 21322312 shuffles=
      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.
      shuffleplace 1place 2place 3new bests
      1, 2, 3yesyesyes3
      1, 3, 2yesyes2
      2, 1, 3yesyes2
      2, 3, 1yesyes2
      3, 1, 2yes1
      3, 2, 1yes1
      in all63211
      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 kk is a new best when it is the biggest of the first kk. Trade place kk with another of the first kk: a biggest at one moves to the other, and trading back undoes it. So it stands equally often at each of the first kk places: at place kk in 1 of every kk shuffles. For 3, the 3 stands at each place in 2 of 6.

    2. the move: add the chances

      the line:
      R=1+12+13+⋯+1nR = 1 + \frac{1}{2} + \frac{1}{3} + \dots + \frac{1}{n}

      why it is allowed: Let RR 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, RR adds their chances: 1 over kk for place kk, by line 1.

    3. the move: read it

      the line:
      the harmonic sum\begin{gathered} \text{the harmonic sum} \end{gathered}

      why it is allowed: By line 2, the harmonic sum. For 3, 11 over 6, about 1.83, as line 1 counted.

    the whole page: expected cost

    why it is allowed: The kkth put is a new best with chance 1 over kk, 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.

  6. the move: name the harmonic sum

    the line:
    A=(n−1)n4+n−H(n)A = \frac{(n - 1)n}{4} + n - H(n)

    why it is allowed: Line 5's bracket is the harmonic sum, H(n)H(n). For 3, about 1.83, so AA is about 2.67, line 3's 16 over 6.

  7. the move: a ceiling from the dearest order

    the line:
    A≤(n−1)n2A \le \frac{(n - 1)n}{2}

    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.

  8. the move: a simpler ceiling

    the line:
    A≤n22A \le \frac{n^2}{2}

    why it is allowed: As in the smallest-first question's line 8, (n−1)n(n - 1)n is at most nn times nn. For 3, 2.67 is at most 4.5.

  9. the move: read it as a bound

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

    why it is allowed: By line 8.

  10. the move: a floor

    the line:
    A≥(n−1)n4A \ge \frac{(n - 1)n}{4}

    why it is allowed: H(n)H(n) adds nn numbers, each at most 1, so in line 6 nn less H(n)H(n) is at least 0. For 3, 2.67 is at least 1.5.

  11. the move: a simpler floor

    the line:
    A≥n28 for n≥2A \ge \frac{n^2}{8} \text{ for } n \ge 2

    why it is allowed: In line 10, put half of nn for n−1n - 1, which is no bigger by the smallest-first question's line 10. For 4, line 10's 3 is at least 2.

  12. the move: read it as a bound

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

    why it is allowed: By line 11, from 2 numbers on.

  13. the move: ceiling and floor together

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

    why it is allowed: Lines 9 and 12 bound AA by the same growth, n2n^2. At 1,000 numbers, H(n)H(n) is about 7.5, beside about 250,000 pairs in order on average, of 499,500 pairs.

try it on small inputs: over every order of 3 numbers put in, the average AA is about 2.67

Keep the numbers in a row in order instead, each put scanning from the front. How many moves do shuffled numbers make, and how many comparisons and moves in all?
  1. the move: the same comparisons

    the line:
    the row compares eachnumber the chain looks at\begin{gathered} \text{the row compares each} \\ \text{number the chain looks at} \end{gathered}
    putrow beforecompared withmoved alongrow after
    14emptynonenone14
    61414146, 14
    256, 146, 14none6, 14, 25
    96, 14, 256, 1425, 146, 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, AA on average.

  2. the move: a put moves the bigger numbers

    the line:
    a put moves each bigger numberone slot along, from the back\begin{gathered} \text{a put moves each bigger number} \\ \text{one slot along, from the back} \end{gathered}
    the rowslot 1slot 2slot 3slot 4
    before61425
    25 moved61425
    14 moved61425
    9 written691425
    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.

  3. the move: a move is a pair out of order

    the line:
    each move is a pair out of order:a bigger number put in first\begin{gathered} \text{each move is a pair out of order:} \\ \text{a bigger number put in first} \end{gathered}

    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.

  4. the move: average them

    the line:
    M=the averagepairs out of order\begin{gathered} M = \text{the average} \\ \text{pairs out of order} \end{gathered}

    why it is allowed: MM is the moves averaged over every order of nn 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 MM is 9 over 6, 1.5.

  5. the move: use the page on expected cost

    the line:
    M=(n−1)n4M = \frac{(n - 1)n}{4}
    where does this come from?
    question 2 of the page expected costShuffle nn different numbers at random. How many pairs stand out of order, on average?
    1. the move: out of order half the time

      the line:
      a pair stands out of orderwith chance one half\begin{gathered} \text{a pair stands out of order} \\ \text{with chance one half} \end{gathered}
      in order1231322133 shufflesout of order3212313123 shuffles=
      Trading places 1 and 3 pairs each shuffle holding them in order with one holding them out of order, 3 and 3.
      shuffleplaces 1 and 2places 1 and 3places 2 and 3pairs out of order
      1, 2, 30
      1, 3, 2yes1
      2, 1, 3yes1
      2, 3, 1yesyes2
      3, 1, 2yesyes2
      3, 2, 1yesyesyes3
      in all3339
      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.

    2. the move: expected counts add

      the line:
      the expected countadds up the chanceof every pair\begin{gathered} \text{the expected count} \\ \text{adds up the chance} \\ \text{of every pair} \end{gathered}

      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 nn, 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.

    3. the move: one half for each pair

      the line:
      one half timesthe number of pairs\begin{gathered} \text{one half times} \\ \text{the number of pairs} \end{gathered}

      why it is allowed: By line 2 the expected count adds line 1's one half once per pair.

    4. the move: count the pairs

      the line:
      P=12×((n−1)+⋯+1)P = \frac{1}{2} \times \bigl((n - 1) + \dots + 1\bigr)

      why it is allowed: Let PP be the expected count, by line 3 half the number of pairs. The first place pairs with the n−1n - 1 after it, the next with one fewer, down to 1. For 3 places, 2 + 1 is 3 pairs, so 1.5.

    5. the move: add them the other way round

      the line:
      P=12×(1+⋯+(n−1))P = \frac{1}{2} \times \bigl(1 + \dots + (n - 1)\bigr)

      why it is allowed: The same numbers in the other order.

    6. the move: use the page on adding up

      the line:
      P=12×(n−1)((n−1)+1)2P = \frac{1}{2} \times \frac{(n - 1)\bigl((n - 1) + 1\bigr)}{2}
      where does this come from?
      question 1 of the page adding up 1+2+⋯+n1 + 2 + \dots + nFit two staircases of squares together. What shape do they make?
      1. the move: draw the sum as a staircase

        the line:
        S=1+2+⋯+nS = 1 + 2 + \dots + n

        why it is allowed: Let SS be the sum of the whole numbers from 1 to nn. Draw it as a staircase, a column for each number: 1 square, then 2, and so on up to nn. For 5, columns of 1, 2, 3, 4 and 5 hold 15 squares.

      2. the move: take two staircases

        the line:
        2S=2(1+2+⋯+n)2S = 2(1 + 2 + \dots + n)

        why it is allowed: Two staircases hold twice the squares. Doubling both sides of line 1 keeps it true.

      3. the move: fit them into a rectangle

        the line:
        2S=n(n+1)2S = n(n + 1)
        Blue stands, yellow hangs. Two staircases of 1 to 5 squares fill a rectangle 5 wide and 6 tall, 30 squares. So 1 + 2 + 3 + 4 + 5 is 5 times 6, halved, which is 15.

        why it is allowed: Stand one staircase with its tallest column on the left. Hang the other upside down from the top, its tallest column on the right, as in the picture. The first column holds nn standing and 1 hanging. Each column to the right, the standing one loses a square and the hanging one gains one. So every column holds n+1n + 1, and the nn columns fill a rectangle nn wide and n+1n + 1 tall.

      4. the move: halve both sides

        the line:
        S=n(n+1)2S = \frac{n(n + 1)}{2}

        why it is allowed: Halving both sides of line 3 keeps it true and leaves one SS. For 5, half of 30 is 15.

      the whole page: adding up 1+2+⋯+n1 + 2 + \dots + n

      why it is allowed: The page on adding up 1 to nn 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 nn. Here that is n−1n - 1.

    7. the move: tidy the bracket

      the line:
      P=12×(n−1)n2P = \frac{1}{2} \times \frac{(n - 1)n}{2}

      why it is allowed: (n−1)+1(n - 1) + 1 is nn.

    8. the move: multiply the halves

      the line:
      P=(n−1)n4P = \frac{(n - 1)n}{4}

      why it is allowed: Half of a half is a quarter. For 3, 2 times 3 over 4 is 1.5.

    9. the move: read it

      the line:
      half the pairs,on average\begin{gathered} \text{half the pairs,} \\ \text{on average} \end{gathered}

      why it is allowed: By lines 4 to 7 there are (n−1)n2\frac{(n - 1)n}{2} pairs, and line 8 is half that. For 3, 1.5, as line 1 counted.

    the whole page: expected cost

    why it is allowed: There are 1 + 2 + ... + (n−1)(n - 1) 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.

  6. the move: add the comparisons

    the line:
    M+A=(n−1)n4+(n−1)n4+n−H(n)M + A = \frac{(n - 1)n}{4} + \frac{(n - 1)n}{4} + n - H(n)
    numbersthe row's moves, MMthe chain's looks, AAthe row's comparisons and movesrow over chain
    1022.5about 29.6about 52.1about 1.76
    1002,475about 2,569.8about 5,044.8about 1.96
    1,000249,750about 250,742.5about 500,492.5about 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 AA, the shuffled question's line 6. Add AA 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.

  7. the move: two quarters make a half

    the line:
    M+A=(n−1)n2+n−H(n)M + A = \frac{(n - 1)n}{2} + n - H(n)

    why it is allowed: In line 6, a quarter and a quarter of (n−1)n(n - 1)n make a half. For 4, 6 + 4 less about 2.08, about 7.92. Section 7 sets this count beside the books' clock.

  8. the move: the moves are at most the looks

    the line:
    M+A≤A+AM + A \le A + A

    why it is allowed: For 4, the moves' 3 is at most AA's 4.92, so 7.92 is at most 9.83. Line 5's moves are always at most AA, which adds nn less H(n)H(n), at least 0 by the shuffled question's line 10. So write AA for them in line 6, whose rest is AA again, by the shuffled question's line 6.

  9. the move: a ceiling from the chain's

    the line:
    M+A≤n2M + A \le n^2

    why it is allowed: By the shuffled question's line 8, each AA is at most half of n2n^2. For 4, 9.83 is at most 16.

  10. the move: read it as a bound

    the line:
    M+A∈O(n2)M + A \in O(n^2)

    why it is allowed: By line 9.

  11. the move: the looks alone

    the line:
    M+A≥AM + A \ge A

    why it is allowed: In line 6, the moves' (n−1)n4\frac{(n - 1)n}{4} is at least 0, so leave it out. The rest is AA, by the shuffled question's line 6. For 4, 7.92 is at least 4.92.

  12. the move: a floor from the chain's

    the line:
    M+A≥n28 for n≥2M + A \ge \frac{n^2}{8} \text{ for } n \ge 2

    why it is allowed: By the shuffled question's line 11, AA is at least an eighth of n2n^2 from 2 numbers on. For 4, 4.92 is at least 2.

  13. the move: read it as a bound

    the line:
    M+A∈Ω(n2)M + A \in \Omega(n^2)

    why it is allowed: By line 12, from 2 numbers on.

  14. the move: ceiling and floor together

    the line:
    M+A∈Θ(n2)M + A \in \Theta(n^2)

    why it is allowed: Lines 10 and 13 bound the comparisons and moves by the same growth, n2n^2.

try it with a small nn: at n=3n = 3, line 4 gives M=1.5M = 1.5, 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.

5, 12, 20, 33, 41, every step written down
stepthe chainwhat happenslinks followed
1Start with an empty chain, and 5 operations to do.0
25Link 5 in at the start of the chain.50
355 is not bigger than 12, so walk on past it.51
45, 12Link 12 in at the end of the chain.5, 121
55, 125 is not bigger than 20, so walk on past it.5, 122
65, 1212 is not bigger than 20, so walk on past it.5, 123
75, 12, 20Link 20 in at the end of the chain.5, 12, 203
85, 12, 205 is not bigger than 33, so walk on past it.5, 12, 204
95, 12, 2012 is not bigger than 33, so walk on past it.5, 12, 205
105, 12, 2020 is not bigger than 33, so walk on past it.5, 12, 206
115, 12, 20, 33Link 33 in at the end of the chain.5, 12, 20, 336
125, 12, 20, 335 is not bigger than 41, so walk on past it.5, 12, 20, 337
135, 12, 20, 3312 is not bigger than 41, so walk on past it.5, 12, 20, 338
145, 12, 20, 3320 is not bigger than 41, so walk on past it.5, 12, 20, 339
155, 12, 20, 3333 is not bigger than 41, so walk on past it.5, 12, 20, 3310
165, 12, 20, 33, 41Link 41 in at the end of the chain.5, 12, 20, 33, 4110
175, 12, 20, 33, 41Done. The chain holds 5 numbers.5, 12, 20, 33, 4110

In all, 10 links followed. The formula from section 4, (n−1)n2\frac{(n - 1)n}{2}, gives W=10W = 10 at n=5n = 5: 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

askedin plain wordsanswerthe keys after
list(d)list the keys[31, 8, 50]31, 8, 50
d.move_to_end(31)move 31 to the endNone8, 50, 31
d.move_to_end(50, last=False)move 50 to the frontNone50, 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
An OrderedDict called d, made by OrderedDict.fromkeys([31, 8, 50]), so each key's value is None, Python's word for no value.
chainbeforeafter
first5, 8, 135
second2, 212, 8, 13, 21
Splicing 8 and 13 from the first chain into the second, after 2, in chains linked one way as on this page. Three pointers change, 5's, 2's and 13's. Linked both ways, as std::list is, back pointers change too.
momentthe rowthe pointer to slot 2 finds
before6, 14, 2514
after putting 9 in6, 9, 14, 259, not 14
A pointer kept to 14 in a row. Putting 9 in shifts 14 one slot along, so the pointer now finds 9. In a chain, 14's place never moves.

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 nn shuffled numbers in, one at a time.

wayfind the placeput it inn shuffled numbers in, on averageextra memoryreach for it when
a chain of placeswalk from the start2 pointers change(n−1)n4+n−H(n)\frac{(n - 1)n}{4} + n - H(n) looksa pointer beside each numberyou splice runs of places in whole, pointers must stay valid, or records are large or cannot move
a row in orderscan from the front, the same comparisonsmove each bigger number along(n−1)n2+n−H(n)\frac{(n - 1)n}{2} + n - H(n) comparisons and movesspare room, if the row doublesalmost always: the books' default
Section 4 works out each count.
numbersthe chain's work over the row'sthe chain's time over the row's
1,0000.501.9
4,0000.496.8
8,0000.507.9
16,0000.509.7
32,0000.5014.5
Sebastian Bourges' books timed this contest up to 32,000 numbers (volume two, chapter 22): 'The linked list does half the work and takes fourteen and a half times as long'. The work stays about half, yet the time gap grows with nn.
address01234567a rowa chainwait 191142263314wait 114319126wait 214231926wait 314319263wait 414314926
  • 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
The same 4 numbers in memory, read from a row and from a chain. Each read waits on slow memory. The row's addresses are known ahead, so its 4 reads share one wait. The chain's next address is known only when the read before it ends, so its reads wait in turn (volume two, chapter 22). So each look in a chain takes longer than each comparison or move in a row.