Skip to content

Kruskal's cheapest links

networks

Level 2 of 3

Also called Kruskal's algorithm and Minimum spanning forest.

how it works

The idea on a small map, then the whole method on the town of eight.

Kruskal's method joins every place it can with the least road in all, as when wiring a town, and has no starting place. Each place starts as a group of its own, named by its letter. Put the roads in order, shortest first, two equal in letter order. Then take each in turn. If its ends have different names, keep it, and the smaller group takes the other's name. If the two groups are the same size, the group of the road's second letter does. If its ends share a name, they are joined already, so the road would close a loop: leave it out. A map in pieces ends with a name for each piece. Putting the roads in order is the sort, here merge sort. This page counts its comparisons, each a look at two roads to see which goes first. The town of eight makes 32, against 12 new names and 24 names read, 2 for each of the 12 roads. The code below, in the language Python, keeps the same names, and leaves the sort to Python's own sorted.

92213ABCEF
The roads kept, heavy, add up to 1 + 2 + 2 + 3, which is 8. A to B, length 9, is left out.
roadits ends' namesdoesnames of A, B, C, E, F
startA B C E F
B-F 1B, FkeepA B C E B
A-E 2A, EkeepA B C A B
E-F 2A, BkeepA A C A A
B-C 3A, CkeepA A A A A
A-B 9A, Aleave outA A A A A
The roads in order. A-E comes before E-F, both 2, by letter. At E-F the groups are the same size, so F's group takes the name.
Wiring a town of eight places: 8 moments of its 15 steps, the steps between them left for the watch page
  1. step 1 of 15

    426531728324AABBCCDDEEFFGGHH

    Every one of the 8 places starts as a group of its own, named by its letter.

    what it remembers to know where it is
    road taken
    not yet
    road kept
    0

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

    watch from here

  2. step 2 of 15

    426531728324AABBCCDDEEFFGGHH

    Put the 12 roads in order from the shortest up, ties in letter order: that takes 32 comparisons. Now take each in turn.

    what it remembers to know where it is
    road taken
    not yet
    road kept
    0

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

    watch from here

  3. step 3 of 15

    426531728324AABBCCDDEEFBGGHH

    The road from B to F is 1 long and joins two groups, so keep it. F takes the name B, since that group is at least as big.

    what it remembers to know where it is
    road taken
    B-F
    road kept
    1

    watch from here

  4. step 7 of 15

    426531728324AABACCDDEAFAGCHD

    The road from E to F is 3 long and joins two groups, so keep it. B and F take the name A, since that group is at least as big.

    what it remembers to know where it is
    road taken
    E-F
    road kept
    10

    watch from here

  5. step 9 of 15

    426531728324AABACCDCEAFAGCHC

    The road from A to B is 4 long, but both are in the group named A already, so it would close a loop. Leave it out.

    what it remembers to know where it is
    road taken
    A-B
    road kept
    13

    watch from here

  6. step 11 of 15

    426531728324AABACADAEAFAGAHA

    The road from B to C is 5 long and joins two groups, so keep it. C, D, G and H take the name A, since that group is at least as big.

    what it remembers to know where it is
    road taken
    B-C
    road kept
    18

    watch from here

  7. step 14 of 15

    426531728324AABACADAEAFAGAHA

    The road from C to D is 8 long, but both are in the group named A already, so it would close a loop. Leave it out.

    what it remembers to know where it is
    road taken
    C-D
    road kept
    18

    watch from here

  8. step 15 of 15

    426531728324AABACADAEAFAGAHA

    Done: every road has been taken. The 7 roads kept are 18 long in all, and the places make one group.

    what it remembers to know where it is
    road taken
    not yet
    road kept
    18

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

    watch from here

the steps, in plain words
  1. every place starts as a group of its own, named by its letterPython lines 12, 13, 14, 15, 16 and 17
  2. put the roads in order from the shortest up, ties in letter order, and take each in turnPython lines 20 and 21
  3. a road between two groups: keep it; the smaller group, or on a tie the second place's, takes the other's namePython lines 25, 26, 27, 28, 29 and 30
  4. a road inside one group would close a loop: leave it outPython lines 22, 23 and 24
  5. the roads kept are the cheapest that join every place that can be joinedPython lines 31 and 36
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.

def kruskal(roads):
    """Find the cheapest links that join every place that can be joined.

    roads is a list of (place, place, length), each road running both
    ways. Returns each place's name at the end: places with one name are
    joined, so a map in pieces ends with a name for each piece.
    """
    return take_in_order(roads)[0]


def take_in_order(roads):
    names = {}  # each place's name: every place starts as a group of its own
    groups = {}  # each name's places
    for a, b, _ in roads:
        for place in (a, b):
            names[place] = place
            groups[place] = [place]
    kept = []
    # the shortest first, two equal in letter order
    in_order = sorted(roads, key=lambda road: (road[2], road[0] + road[1]))
    for a, b, length in in_order:
        keep, lose = names[a], names[b]  # on a tie, lose is the second place's
        if keep == lose:  # one group already: it would close a loop
            continue  # so leave it out
        if len(groups[lose]) > len(groups[keep]):  # the smaller takes a new name
            keep, lose = lose, keep
        for place in groups[lose]:
            names[place] = keep
        groups[keep] += groups.pop(lose)
        kept.append((a, b, length))
    return names, kept


def cheapest_links(roads):
    """The roads kept, each as (place, place, length), shortest first."""
    return take_in_order(roads)[1]

how it scales

The plot counts the sort's comparisons on two maps, every length 1 and listed in letter order, so the roads start in order. One is a line of places, each joined to the next, and the other has every pair joined. nn is how many places, measured from 10 to 1,000.

Each mark across or up is ten times the one before. A line climbs a little over one mark up for each mark across: 371 at 100 places and 5,051 at 1,000, about 14 times. Every pair joined climbs a little over two: 33,081 at 100 places and 4,787,336 at 1,000, about 145 times. The plot's note reads every pair further out, on the dashed part, a million to ten million places: about 118 times.

comparisons to order the roads, ten times more at each mark up

a seconda minutean houra dayslope 2.11021041061081010101210141016101102103104105106107a seconda minutean houra dayslope 2.11011021031041051061071081091010101110121013101410151016101102103104105106107a seconda minutean houra dayslope 2.11011021031041051061071081091010101110121013101410151016101102103104105106107

nn, n, ten times more at each mark to the right

  • every pair, every length 1solid where measured by running it; dashed where its formula carries it on to ten millionslope 2.1: ten times n, 118 times the work
  • a line, every length 1solid where measured by running it; dashed where its formula carries it on to ten million
how long every pair joined takes, at a billion comparisons a second
nncomparisons to order the roadstime
1,0004,787,336about 4.8 milliseconds
100,00083,738,380,752about 1.4 minutes
10,000,0001,154,820,797,287,168about 13 days

The comparisons to order the roads 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 Kruskal's comparisons yourself, as the plot on this page does.

Run it with Python 3.12 or later. For each size n it runs two maps of n
places, every length 1: a line, the fewest roads that join them, and every
two places joined, the most. It prints the comparisons the sort makes for
each, by count below, the watch page's merge in place of Python's own
sorted. The counts are the same on any computer; only the time differs.
"""


def kruskal(roads):
    """Find the cheapest links that join every place that can be joined.

    roads is a list of (place, place, length), each road running both
    ways. Returns each place's name at the end: places with one name are
    joined, so a map in pieces ends with a name for each piece.
    """
    return take_in_order(roads)[0]


def take_in_order(roads):
    names = {}  # each place's name: every place starts as a group of its own
    groups = {}  # each name's places
    for a, b, _ in roads:
        for place in (a, b):
            names[place] = place
            groups[place] = [place]
    kept = []
    # the shortest first, two equal in letter order
    in_order = sorted(roads, key=lambda road: (road[2], road[0] + road[1]))
    for a, b, length in in_order:
        keep, lose = names[a], names[b]  # on a tie, lose is the second place's
        if keep == lose:  # one group already: it would close a loop
            continue  # so leave it out
        if len(groups[lose]) > len(groups[keep]):  # the smaller takes a new name
            keep, lose = lose, keep
        for place in groups[lose]:
            names[place] = keep
        groups[keep] += groups.pop(lose)
        kept.append((a, b, length))
    return names, kept


def cheapest_links(roads):
    """The roads kept, each as (place, place, length), shortest first."""
    return take_in_order(roads)[1]


def count(roads):
    """How many comparisons the watch page's sort makes: runs of 1, 2, 4
    and on, merged in neighbouring pairs, comparing their front roads."""
    runs = [[(length, a + b)] for a, b, length in roads]
    compared = 0
    while len(runs) > 1:
        merged = []
        for k in range(0, len(runs) - 1, 2):
            left, right = runs[k], runs[k + 1]
            run = []
            i = j = 0
            while i < len(left) and j < len(right):
                compared += 1
                if right[j] < left[i]:
                    run.append(right[j])
                    j += 1
                else:
                    run.append(left[i])
                    i += 1
            merged.append(run + left[i:] + right[j:])
        if len(runs) % 2 == 1:
            merged.append(runs[-1])
        runs = merged
    return compared


def line(n):
    """n places in a line, p0001 onward, each road 1 long: n - 1 roads."""
    return [(f"p{k:04}", f"p{k + 1:04}", 1) for k in range(1, n)]


def every_pair(n):
    """n places, every two joined, each road 1 long: n(n - 1) / 2 roads."""
    return [(f"p{a:04}", f"p{b:04}", 1) for a in range(1, n + 1) for b in range(a + 1, n + 1)]


if __name__ == "__main__":
    print(f"{'n':>6} {'a line':>8} {'every pair':>12}")
    for n in [10, 100, 1000]:
        print(f"{n:>6} {count(line(n)):>8} {count(every_pair(n)):>12}")

best, worst and average

Here best just names a line and worst names every pair: kinds of map, not the fewest and most a sort can compare. The same roads in another order can compare differently: section 4, question 1. No average is worked out. With 8 places the sort compares 11 on a line, 32 on the town of eight and 72 with every pair joined.

A case is one kind of map, such as a line. A bound says how fast that case's cost grows as places are added.

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
besta line, every length 1worstevery pair, every length 1
comparisons to order the roadsa1+a2+a4+…a_1 + a_2 + a_4 + \dots on n−1n - 1 roads, each round's left runsa1+a2+a4+…a_1 + a_2 + a_4 + \dots on n(n−1)2\frac{n(n - 1)}{2} roads, each round's left runs
roads looked alongn−1n - 1, each road oncen(n−1)2\frac{n(n - 1)}{2}, each road once
roads keptn−1n - 1n−1n - 1
how the comparisons to order the roads grow in each case
tight, Θ\ThetaΘ(n log⁡2 n)\Theta(n \,\log_2\, n)Θ(n2 log⁡2 n)\Theta(n^2 \,\log_2\, n)
ceiling, OOO(n log⁡2 n)O(n \,\log_2\, n)O(n2 log⁡2 n)O(n^2 \,\log_2\, n)
floor, Ω\OmegaΩ(n log⁡2 n)\Omega(n \,\log_2\, n)Ω(n2 log⁡2 n)\Omega(n^2 \,\log_2\, n)

extra memory: A name and a spot in a group's list for each place, a second row of mm roads for the sort, and the roads kept.

Extra memory is the room it needs on top of the input itself, while it runs.

1111ABCDE
A line of 5, every length 1. All 4 roads are kept.
1111111111ABCDE
Every pair of 5, every length 1. Of 10 roads, 4 are kept.
maproadscomparisonskept
a line of 5444
every pair of 510214
a line of 87117
the town of eight12327
every pair of 828727
Every map of 8 places in one piece keeps 7 roads.

where the formula comes from

Questions 1 to 3 count the comparisons, 4 and 5 the whole method, and 6 shows why the roads kept are cheapest.

Question 1: in whatever order mm roads come, how many comparisons does the sort make? Let SS be a ceiling on them.
  1. the move: how the sort goes

    the line:
    runs of 1,2,4,…merged in pairs\begin{gathered} \text{runs of } 1, 2, 4, \dots \\ \text{merged in pairs} \end{gathered}
    the row: 3, 1, 5, 2, 8, 4, 7, 611111111start2222round 144round 28round 32a run, its length insidethe first runall in one runa merge in round 2, its numbers13251235goes straight in, the other run used up
    8 numbers stand for 8 roads. Round 2's first merge, 1, 3 with 2, 5, compares 1 with 2, then 3 with 2, then 3 with 5. That is 3 comparisons. The 5 follows with no comparison.
    roundrun lengthmergescomparisons
    1166
    2238
    3417
    48111
    all1132
    The town of eight, in the watch page's order: A-B, A-E, A-F, B-C, E-F, B-F, F-G, C-G, C-D, G-H, D-H, D-G. In round 3 the last run of 4 waits.

    why it is allowed: This sort is merge sort. Each road starts as a run of 1. Each round merges neighbouring runs, comparing their front roads and taking the one that goes first. A last run with no partner waits.

  2. the move: a round's most

    the line:
    each round:at most m\begin{gathered} \text{each round:} \\ \text{at most } m \end{gathered}

    why it is allowed: Each comparison puts one road into the new run, and a round moves each road once at most. The town's rounds are all at most 12.

  3. the move: how many rounds

    the line:
    ⌈log⁡2 m⌉ rounds\lceil \log_2\, m \rceil \text{ rounds}
    numberlog× 2+ 11021428316452.32123.58
    Top, numbers, each double the last; bottom, their logs, each 1 more. 5 lies between 4 and 8, so its log, about 2.3, lies between 2 and 3. 12 lies between 8 and 16, so its log, about 3.6, lies between 3 and 4.

    why it is allowed: Run lengths double until one run holds all mm. For 12 roads, 1, 2, 4 and 8, so 4 rounds. The log of 12 is about 3.6, and rounded up, 4.

  4. the move: a ceiling

    the line:
    S=m⌈log⁡2 m⌉S = m \lceil \log_2\, m \rceil

    why it is allowed: SS is lines 2 and 3 multiplied. For 12 roads, 48.

  5. the move: a merge's least

    the line:
    a merge compares at leastits right run’s length\begin{gathered} \text{a merge compares at least} \\ \text{its right run's length} \end{gathered}
    8 roadscomparisons
    in order12
    back to front12
    the dearest order17
    Order can change the count. Every order of 8 costs 12 to 17, between the floor of 6 and the ceiling of 24 this question reaches.

    why it is allowed: A merge stops when a run is used up, and each road of that run took one comparison. The right run is never the longer. So 1, 3 with 2, 5 compares 3 times, at least 2.

  6. the move: a round's right runs

    the line:
    runs of r, with 2r at most m:at least m4 roads in right runs\begin{gathered} \text{runs of } r \text{, with } 2r \text{ at most } m \text{:} \\ \text{at least } \frac{m}{4} \text{ roads in right runs} \end{gathered}

    why it is allowed: At least one full pair fits, and what is left over is shorter than a pair, so the full pairs hold at least half the roads. Half of each pair is its right run. For 12 roads in runs of 4, one pair holds 8, so 4 in right runs, at least 3.

  7. the move: how many such rounds

    the line:
    ⌊log⁡2 m⌋ such rounds\lfloor \log_2\, m \rfloor \text{ such rounds}

    why it is allowed: Run lengths 1, 2, 4 and on, while twice the length is at most mm. For 12 roads, 1, 2 and 4, so 3, which is the log of 12 rounded down.

  8. the move: a floor

    the line:
    comparisons: at leastm4⌊log⁡2 m⌋\begin{gathered} \text{comparisons: at least} \\ \frac{m}{4} \lfloor \log_2\, m \rfloor \end{gathered}

    why it is allowed: By lines 5 and 6, each such round compares at least m4\frac{m}{4}. Line 7 counts those rounds, so multiply. For 12 roads, 9. The town's 32 lies between 9 and 48.

try it with a small mm: at m=12m = 12, line 4 gives S=48S = 48, which you can work out by hand

Question 2: how many comparisons, KK, does a line of nn places make, every length 1?
  1. the move: a line's roads

    the line:
    a line of n places:n−1 roads\begin{gathered} \text{a line of } n \text{ places:} \\ n - 1 \text{ roads} \end{gathered}

    why it is allowed: The first place needs no road, and each place after it adds one. So mm is n−1n - 1.

  2. the move: each merge compares its left run

    the line:
    K=a1+a2+a4+…K = a_1 + a_2 + a_4 + \dots
    run lengthleft runscomparisons
    14 of 14
    22 of 24
    41 of 44
    all12
    A line of 9, so 8 roads.

    why it is allowed: Every length is 1 and the roads come in letter order, so the list is in order already. A merge takes all its left run first, one comparison each, then stops. a1a_1 adds up the left runs of length 1, a2a_2 those of length 2, and so on. Lengths double, so there is no a3a_3. Here 4 + 4 + 4.

  3. the move: a ceiling

    the line:
    K≤(n−1)⌈log⁡2(n−1)⌉K \le (n - 1) \lceil \log_2 (n - 1) \rceil

    why it is allowed: Question 1's line 4, with mm as n−1n - 1. For 5 places, KK is 4, at most 8.

  4. the move: a simpler ceiling

    the line:
    K≤2n log⁡2 nK \le 2n \,\log_2\, n

    why it is allowed: n−1n - 1 is below nn, both times it appears. Rounding up adds less than 1, and from 2 places on 1 is at most log⁡2 n\log_2\, n, so the rounded log is at most 2 log⁡2 n2 \,\log_2\, n. For 5 places, KK is 4, at most 23.2.

  5. the move: read the bound

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

    why it is allowed: By line 4, with the fixed multiple 2.

  6. the move: a floor

    the line:
    K≥n−14⌊log⁡2(n−1)⌋K \ge \frac{n - 1}{4} \lfloor \log_2 (n - 1) \rfloor

    why it is allowed: Question 1's line 8. For 5 places, KK is 4, at least 2.

  7. the move: n - 1 is at least half of n

    the line:
    K≥n8⌊log⁡2(n−1)⌋K \ge \frac{n}{8} \lfloor \log_2 (n - 1) \rfloor

    why it is allowed: From 2 places on. For 5 places, KK is 4, at least 1.25.

  8. the move: the rounded log against the exact one

    the line:
    n is at most 2k+1, so  log⁡2 nis at most k+1, at most 2k\begin{gathered} n \text{ is at most } 2^{k + 1}, \text{ so } \,\log_2\, n \\ \text{is at most } k + 1, \text{ at most } 2k \end{gathered}

    why it is allowed: Call line 7's rounded-down log kk. From 3 places on kk is at least 1, so k+1k + 1 is at most 2k2k. n−1n - 1 is below 2k+12^{k + 1}, so nn is at most it. For 5 places, kk is 2, and the log of 5, about 2.3, is at most 3, at most 4.

  9. the move: drop the rounding

    the line:
    K≥n log⁡2 n16K \ge \frac{n \,\log_2\, n}{16}

    why it is allowed: By line 8, kk is at least half of log⁡2 n\log_2\, n. Put that into line 7. For 5 places, KK is 4, at least 0.73.

  10. the move: read the bound

    the line:
    K∈Ω(n log⁡2 n)K \in \Omega(n \,\log_2\, n)

    why it is allowed: By line 9, with the fixed multiple a sixteenth.

  11. the move: both together

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

    why it is allowed: Lines 5 and 10 bound KK by the same growth.

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

Question 3: how many comparisons, WW, does every pair of nn places make, every length 1?
  1. the move: as on a line of places

    the line:
    W=a1+a2+a4+…W = a_1 + a_2 + a_4 + \dots
    run lengthleft runscomparisons
    15 of 15
    22 of 24
    41 of 44
    81 of 88
    all21
    Every pair of 5, so 10 roads. At run length 2 the last run waits, and at 4 the last 2 roads wait.

    why it is allowed: As in question 2, the list is in order already, so each merge compares its left run.

  2. the move: how many roads

    the line:
    W=a1+a2+a4+…,m=n(n−1)2\begin{gathered} W = a_1 + a_2 + a_4 + \dots, \\ m = \frac{n(n - 1)}{2} \end{gathered}
    where does this come from?
    question 2 of the page graphs and their wordsnn places, every two joined by a road. How many roads?
    1. the move: count place by place

      the line:
      R=(n−1)+⋯+2+1R = (n - 1) + \dots + 2 + 1
      ABCDE
      Every two of 5 places joined. A has 4 roads, B 3 more, C 2 more, D 1 more, E none new. 4 + 3 + 2 + 1 = 10.

      why it is allowed: Let RR be the roads, for 2 places or more. List the places. The first has roads to the n−1n - 1 after it. The next adds one fewer new road, as its road to the first is counted already. Each adds one fewer, and the last adds none.

    2. the move: use adding up 1 to n

      the line:
      R=n(n−1)2R = \frac{n(n - 1)}{2}
      placenew roads
      A4
      B3
      C2
      D1
      E0
      all10
      The new roads each place adds on line 1's map, in turn. 4 + 3 + 2 + 1 + 0 = 10.
      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: Read from right to left, line 1 is 1 + 2 + up to n−1n - 1. The box under this line adds 1 up to a last number with two staircases, that number times one more, halved. Here the last number is n−1n - 1. One more than it is nn, so RR is n−1n - 1 times nn, halved. For 5, 1 + 2 + 3 + 4 is 4 times 5, halved, which is 10.

    3. the move: one way, each pair holds two

      the line:
      one way:U is twice R\begin{gathered} \text{one way:} \\ U \text{ is twice } R \end{gathered}

      why it is allowed: Let UU be the most one-way roads. A to B and B to A are two roads, one each way, so each pair holds two.

    4. the move: double line 2

      the line:
      U=2R=n(n−1)U = 2R = n(n - 1)

      why it is allowed: Line 3 says UU is 2R2R, and twice line 2 is n(n−1)n(n - 1). For 5 places, 20.

    5. the move: read it

      the line:
      5 places: 10 roads, or 20 one way1,000 places: 499,500 roads\begin{gathered} 5 \text{ places: 10 roads, or 20 one way} \\ 1{,}000 \text{ places: } 499{,}500 \text{ roads} \end{gathered}

      why it is allowed: 1,000 times 999, halved, is 499,500. A map of 1,000 places with 3,000 roads has 3 times as many roads as places, a few, so it is sparse. It holds 3,000 of the 499,500 it could.

    the whole page: graphs and their words

    why it is allowed: How many roads every pair has, shown under this line. For 5 places, 10.

  3. the move: a ceiling

    the line:
    W≤m⌈log⁡2 m⌉W \le m \lceil \log_2\, m \rceil

    why it is allowed: Question 1's line 4. For 5 places, WW is 21, at most 40.

  4. the move: a log of n

    the line:
    m is at most n22, so ⌈log⁡2 m⌉is at most 2 log⁡2 n\begin{gathered} m \text{ is at most } \frac{n^2}{2}, \text{ so } \lceil \log_2\, m \rceil \\ \text{is at most } 2 \,\log_2\, n \end{gathered}

    why it is allowed: Line 2 gives mm at most this. Squaring doubles a log: the log of 4 is 2, and of 16, its square, 4. Halving takes 1 off, and rounding up adds back less than 1. For 5 places, mm is 10, whose log rounded up is 4, at most 4.6.

  5. the move: use it

    the line:
    W≤2m log⁡2 nW \le 2m \,\log_2\, n

    why it is allowed: By lines 3 and 4. For 5 places, WW is 21, at most 46.4.

  6. the move: roads by places

    the line:
    W≤n2 log⁡2 nW \le n^2 \,\log_2\, n

    why it is allowed: 2m2m is n(n−1)n(n - 1), at most n2n^2. For 5 places, WW is 21, at most 58.

  7. the move: read the bound

    the line:
    W∈O(n2 log⁡2 n)W \in O(n^2 \,\log_2\, n)

    why it is allowed: By line 6, with the fixed multiple 1.

  8. the move: a floor

    the line:
    W≥m4⌊log⁡2 m⌋W \ge \frac{m}{4} \lfloor \log_2\, m \rfloor

    why it is allowed: Question 1's line 8. For 5 places, WW is 21, at least 7.5.

  9. the move: m is at least a quarter of n squared

    the line:
    W≥n216⌊log⁡2 m⌋W \ge \frac{n^2}{16} \lfloor \log_2\, m \rfloor

    why it is allowed: From 2 places on, n−1n - 1 is at least half of nn, so mm is at least a quarter of n2n^2, and a quarter of mm at least n216\frac{n^2}{16}. For 5 places, WW is 21, at least 4.7.

  10. the move: the rounded log against the exact one

    the line:
    n is below 2k+1, so  log⁡2 nis at most 2k\begin{gathered} n \text{ is below } 2^{k + 1}, \text{ so } \,\log_2\, n \\ \text{is at most } 2k \end{gathered}

    why it is allowed: From 3 places on, mm is at least nn. Call line 9's rounded-down log kk, at least 1. mm is below 2k+12^{k + 1}, so nn is too. Then as in question 2's line 8. For 5 places, mm is 10 and kk is 3, and the log of 5, about 2.3, is at most 6.

  11. the move: drop the rounding

    the line:
    W≥n2 log⁡2 n32W \ge \frac{n^2 \,\log_2\, n}{32}

    why it is allowed: By line 10, kk is at least half of log⁡2 n\log_2\, n. Put that into line 9. For 5 places, WW is 21, at least 1.8.

  12. the move: read the bound

    the line:
    W∈Ω(n2 log⁡2 n)W \in \Omega(n^2 \,\log_2\, n)
    comparisonsplaces01002003004000246810comparisonsplaces01002003004000246810
    • n2 log⁡2 nn^2 \,\log_2\, n
    • WW
    • n2 log⁡2 n32\frac{n^2 \,\log_2\, n}{32}
    From 3 places on, WW stays between its floor and its ceiling.

    why it is allowed: By line 11, with the fixed multiple a thirty-second.

  13. the move: both together

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

    why it is allowed: Lines 7 and 12 bound WW by the same growth.

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

Question 4: each road kept writes new names. Why are at most n log⁡2 nn \,\log_2\, n written?
  1. the move: a new name, a bigger group

    the line:
    a place renamed ends in agroup at least twice as big\begin{gathered} \text{a place renamed ends in a} \\ \text{group at least twice as big} \end{gathered}
    road kepttake a new namehow many
    B-FF1
    A-EE1
    C-GG1
    D-HH1
    E-FB, F2
    G-HD, H2
    B-CC, D, G, H4
    all12
    The town of eight. H is renamed most, 3 times, its group growing 1, 2, 4, 8. So 8 places times 3 is a ceiling of 24, and the town writes 12.

    why it is allowed: Only the smaller group takes a new name, or if the two are the same size, the second letter's. So the other group is at least as big, and together they are at least double.

  2. the move: each place's most

    the line:
    each place: at mostlog⁡2 n new names\begin{gathered} \text{each place: at most} \\ \log_2\, n \text{ new names} \end{gathered}

    why it is allowed: Its group starts at 1, at least doubles each time, and never holds more than nn. For 8 places, 1, 2, 4 and 8, so 3.

  3. the move: every place

    the line:
    Y=n log⁡2 n,a ceiling on new names\begin{gathered} Y = n \,\log_2\, n, \\ \text{a ceiling on new names} \end{gathered}

    why it is allowed: Line 2 times the nn places. The letters at the start do not count. For 8, 24.

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

Question 5: why does the whole method grow no faster than m log⁡2 nm \,\log_2\, n?
  1. the move: three costs

    the line:
    comparisons, new names,names read\begin{gathered} \text{comparisons, new names,} \\ \text{names read} \end{gathered}
    the town of eightcount
    comparisons32
    new names12
    names read24
    all68
    The town of eight's three costs.

    why it is allowed: Comparisons by question 1 and new names by question 4. Each of the mm roads then reads 2 names, to test them.

  2. the move: the sort

    the line:
    comparisons: at most2m log⁡2 n\begin{gathered} \text{comparisons: at most} \\ 2m \,\log_2\, n \end{gathered}

    why it is allowed: Comparisons are at most m⌈log⁡2 m⌉m \lceil \log_2\, m \rceil, by question 1's line 4. Two places share one road at most, so question 3's line 4 holds on any map. For the town, 48 is at most 72.

  3. the move: the new names

    the line:
    new names: at most2m log⁡2 n\begin{gathered} \text{new names: at most} \\ 2m \,\log_2\, n \end{gathered}

    why it is allowed: By question 4, at most n log⁡2 nn \,\log_2\, n. Every place here is on a road, and a road has 2 ends, so nn is at most 2m2m, even in pieces. For the town, 24 is at most 72.

  4. the move: the names read

    the line:
    N=2mN = 2m

    why it is allowed: NN is the names read to test the roads, 2 for each. From 2 places on log⁡2 n\log_2\, n is at least 1, so NN is at most 2m log⁡2 n2m \,\log_2\, n. For the town, 24 is at most 72.

  5. the move: add the three

    the line:
    these three: at most6m log⁡2 n\begin{gathered} \text{these three: at most} \\ 6m \,\log_2\, n \end{gathered}

    why it is allowed: Lines 2, 3 and 4 each allow 2m log⁡2 n2m \,\log_2\, n, and three lots make 6. For the town, 6 times 12 times 3 is 216, and its three cost 68.

  6. the move: read the bound

    the line:
    the whole method in O(m log⁡2 n),in books, O(E log⁡2 V)\begin{gathered} \text{the whole method in } O(m \,\log_2\, n), \\ \text{in books, } O(E \,\log_2\, V) \end{gathered}

    why it is allowed: By line 5, with the fixed multiple 6 for these three. The method also writes each place's starting letter, at most 2m2m, and in merges moves each road at most once a round, so again at most line 2's ceiling. The code keeps each name's places in a list, so finding a group looks at no other place. What remains is a fixed few steps for each road or new name. Those are only more lots of 2m log⁡2 n2m \,\log_2\, n, so the whole method has a larger multiple, still fixed, on any map, even in pieces.

try it with a small mm: at m=12m = 12, line 4 gives N=24N = 24, which you can work out by hand

Question 6: why are the roads kept a cheapest network, one for each piece? Let ww be a network's cost and TT its cost after one swap.
  1. the move: what stays true

    the line:
    the roads kept so far liein some cheapest network\begin{gathered} \text{the roads kept so far lie} \\ \text{in some cheapest network} \end{gathered}

    why it is allowed: Take one piece, and only its roads. Two networks can tie for cheapest. At the start no road is kept, so there is nothing to check. The plan is to show that keeping the next road keeps this true.

  2. the move: split the places

    the line:
    a road kept: cheapestacross its split\begin{gathered} \text{a road kept: cheapest} \\ \text{across its split} \end{gathered}
    92213ABCEF
    A and E, shaded, are split from the rest. E to F, length 2, and A to B, length 9, cross.

    why it is allowed: Take the next road kept. Split the group at one of its ends from the rest of the piece. Its ends have different names, so it crosses. An earlier road was kept or left out, so its ends now share a name, and it does not cross. A later road is no shorter. So this road is cheapest across. On the small map, with A and E split off, it is E to F.

  3. the move: swap a road on the loop

    the line:
    T=w−9+2T = w - 9 + 2
    29132ABCEF
    The network of 15 with E to F added. The loop, heavy, crosses the split on E to F and on A to B.

    why it is allowed: Take a network with the roads kept so far, B to F and A to E, without E to F: those two, plus A to B and B to C. That costs 1 + 2 + 9 + 3, so ww is 15. Adding E to F closes a loop, which comes back across the split on A to B, length 9. Take A to B out.

  4. the move: add them up

    the line:
    T=w−7T = w - 7
    where does this come from?
    question 2 of the page greedy choices, and when they failSplit the places in two. Why does some cheapest network hold the cheapest road across? Let ww be a network's cost, and TT its cost after one swap.
    1. the move: swap a road on the loop

      the line:
      T=w−6+4T = w - 6 + 4
      36214ABCDE
      A network of 12, A to B, B to D, C to D and D to E, with A to C added. The loop A, C, D, B, A, heavy, crosses back on B to D, of 6.

      why it is allowed: The plan is to show a swap on a network that is not the cheapest, then use it on a cheapest one. Take a network without A to C, the cheapest road across. A to B, B to D, C to D and D to E cost 3 + 6 + 2 + 1, so here ww is 12. They already join A to C another way, so adding A to C closes a loop, roads leading round and back to A. The loop leaves the shaded group on A to C, so it comes back on another road across, B to D, of 6. Take B to D out.

    2. the move: add them up

      the line:
      T=w−2T = w - 2

      why it is allowed: Taking out 6 and putting in 4 is 2 less.

    3. the move: no dearer

      the line:
      T≤wT \le w
      3421ABCDE
      After the swap, B to D out and A to C in, at 12 less 2, which is 10.

      why it is allowed: ww less 2 is at most ww, so the swap costs no more. Before, 12; after, 10.

    4. the move: still one piece

      the line:
      every placestill joined\begin{gathered} \text{every place} \\ \text{still joined} \end{gathered}

      why it is allowed: A trip that used the road taken out goes the other way round the loop. From B to D, that is B, A, C, D.

    5. the move: on any map

      the line:
      cost after:w−f+e\begin{gathered} \text{cost after:} \\ w - f + e \end{gathered}

      why it is allowed: On any map, let ee be the cheapest road across, and ff a road where the loop crosses back. Each letter also stands for its road's length. Here ee is A to C, of 4, and ff is B to D, of 6. The swap takes ff out and puts ee in.

    6. the move: f costs at least e

      the line:
      w−f+eis at most w\begin{gathered} w - f + e \\ \text{is at most } w \end{gathered}

      why it is allowed: ff crosses too, and ee is the cheapest road across, so ff is at least ee. Taking ff out saves at least what putting ee in adds.

    7. the move: start from a cheapest one

      the line:
      a cheapest networkswaps to one with e\begin{gathered} \text{a cheapest network} \\ \text{swaps to one with } e \end{gathered}

      why it is allowed: The network of 12 only showed the swap. Start instead from a cheapest network without ee. The swap costs no more, and no network costs less than a cheapest one, so it costs the same. So it is cheapest too, and holds ee. A cheapest network that holds ee already needs no swap.

    the whole page: greedy choices, and when they fail

    why it is allowed: Taking out 9 and putting in 2 is 7 less. The proof of the swap on any map is under this line.

  5. the move: no dearer

    the line:
    T≤wT \le w

    why it is allowed: The road taken out crosses too, so it costs at least the cheapest across. Before, 15; after, 8.

  6. the move: roads kept stay

    the line:
    no road keptis taken out\begin{gathered} \text{no road kept} \\ \text{is taken out} \end{gathered}

    why it is allowed: The road taken out crosses the split. A road kept has both ends in one group, so it does not cross.

  7. the move: so it stays true

    the line:
    roads kept and the nextlie in a cheapest network\begin{gathered} \text{roads kept and the next} \\ \text{lie in a cheapest network} \end{gathered}

    why it is allowed: The network of 15 only showed the swap. Start from a cheapest network holding the roads kept so far, by line 1. If it holds the next road too, nothing changes. If not, the swap leaves a network and costs no more, and no network costs less, so it is cheapest too. It holds the next road, and by line 6 it keeps the roads kept.

  8. the move: as many roads

    the line:
    a piece of p places:p−1 roads kept\begin{gathered} \text{a piece of } p \text{ places:} \\ p - 1 \text{ roads kept} \end{gathered}
    road keptgroups left
    start5
    B-F4
    A-E3
    E-F2
    B-C1
    The small map, 5 places and 4 roads kept.

    why it is allowed: Each road kept makes one group fewer. After its turn a road's ends share a name, kept or left out. A piece is joined, so two or more groups left in it would have a road between two of them. So a piece of pp places goes from pp groups to 1.

  9. the move: a cheapest network has them too

    the line:
    a cheapest network:p−1 roads\begin{gathered} \text{a cheapest network:} \\ p - 1 \text{ roads} \end{gathered}

    why it is allowed: Take any road off a loop. A trip that used it goes the other way round, so every place stays joined. Every length here is at least 1, so the cost falls. So it has no loop. Travel out from any place. Each other place is first reached along one road, p−1p - 1 in all, and any other road would close a loop.

  10. the move: at the end

    the line:
    the roads kept are acheapest network\begin{gathered} \text{the roads kept are a} \\ \text{cheapest network} \end{gathered}
    13212ABCDEFH
    The roads kept on two parts of town, the watch page's fifth map, cost 6 and 3, which is 9, with 2 names at the end.

    why it is allowed: By line 7, after every road kept they lie in a cheapest network of the piece, and by lines 8 and 9 both have p−1p - 1 roads. So they are all of it, one for each piece.

  11. the move: ties change nothing

    the line:
    ties broken any way:the same total\begin{gathered} \text{ties broken any way:} \\ \text{the same total} \end{gathered}

    why it is allowed: Nothing above used letter order, and all cheapest networks cost the same. On the watch page's third map, every road 5, ties broken backwards keep other roads, and still cost 35.

try it with a small ww: at w=15w = 15, line 3 gives T=8T = 8, which you can work out by hand

count it yourself

Every pair of 3 places: A, B and E. The watch page takes this map as A-B 1, A-E 1, B-E 1. Round 1 makes 1 comparison, A-B with A-E, and B-E waits. Round 2 makes 2, A-B with B-E, then A-E with B-E. So a1a_1 is 1 and a2a_2 is 2: 3 in all, shown together at step 2. Then A-B and A-E are kept, and B-E would close a loop. The last columns are running totals.

A-B 1, A-E 1, B-E 1, every step written down
stepwhat happenscomparisons to order the roadsroads looked alongroads kept
1Every one of the 3 places starts as a group of its own, named by its letter.000
2Put the 3 roads in order from the shortest up, ties in letter order: that takes 3 comparisons. Now take each in turn.300
3The road from A to B is 1 long and joins two groups, so keep it. B takes the name A, since that group is at least as big.311
4The road from A to E is 1 long and joins two groups, so keep it. E takes the name A, since that group is at least as big.322
5The road from B to E is 1 long, but both are in the group named A already, so it would close a loop. Leave it out.332
6Done: every road has been taken. The 2 roads kept are 2 long in all, and the places make one group.332

In all, 3 comparisons to order the roads. The formula from section 4, a1+a2+a4+…a_1 + a_2 + a_4 + \dots, gives W=3W = 3 at n=3n = 3: the same.

where you meet it

A 1956 paper set it out. Ready-made code gives it to you, keeping groups with union-find, where a join rewrites no names.

  • Kruskal's 1956 paper

    Joseph Kruskal set out this method in a paper of under three pages. It is one of three the paper gives: go through the roads by length, and pass over any that would close a loop.

    source: J. B. Kruskal, On the shortest spanning subtree of a graph and the traveling salesman problem (opens in a new tab), Proceedings of the American Mathematical Society 7(1), and the books' volume three, chapter 33

  • networkx's kruskal_mst_edges

    networkx, ready-made Python code for maps of places and roads, uses this method by default for a cheapest network. It sorts the roads, and keeps its groups with union-find.

    source: the networkx source, mst.py (opens in a new tab), its kruskal_mst_edges and minimum_spanning_tree

  • SciPy's minimum_spanning_tree

    SciPy, ready-made Python code for science, sorts a map's roads by length, then keeps its groups with union-find too.

    source: the SciPy source, _min_spanning_tree.pyx (opens in a new tab), its minimum_spanning_tree

what is used instead

When you want the shortest way between two places, use Dijkstra's method. When every pair is joined, Prim's method with a scan, looking through the places each round, grows more slowly than this sort. It grows as the square of nn on Prim's own page, and this sort as the square of nn times log⁡2 n\log_2\, n in question 3.

how it compares

Prim's method starts at one place and grows outward, so it finds a cheapest network of that place's piece. Dijkstra's also grows from a start, and finds shortest ways.

methodpicks next byfinds
Kruskal's methodthe cheapest road left, unless it closes a loopa cheapest network for each piece
Prim's methodthe cheapest road out of its one groupa cheapest network of the start's piece
Dijkstra's methodthe least total length from the startshortest ways from the start
On the small map at the top, Prim's from A takes 2, 2, 1 and 3: the same 8, in another order.
21ABCEF
Kruskal's after 2 roads: three groups, A and E, B and F, and C alone.
22ABCEF
Prim's from A after 2 roads: A, E and F joined; B and C not reached yet.

race them on one row of your own