TExcelTAD
Home › Graph Algorithms › Kruskal's Algorithm with Union-Find

Kruskal's Algorithm with Union-Find

Kruskal's algorithm (1956) is the generic MST method in its simplest form: look at the edges from lightest to heaviest and keep each one that does not close a cycle. It never thinks about a particular tree. At any moment its edges form a forest, and each accepted edge merges two of the forest's trees. The only data-structure question is how to tell quickly whether two vertices are already in the same tree, and the answer is the disjoint-set forest with union by rank and path compression. The DSA course shows the algorithm by example; this lesson proves it, times it and uses it for clustering.

The algorithm

text
KRUSKAL(G, w)
1  A = empty set
2  for each vertex v in G.V:  MAKE-SET(v)
3  sort the edges of G.E into non-decreasing order by weight w
4  for each edge (u, v) in that order
5      if FIND-SET(u) != FIND-SET(v)          // different trees
6          A = A + {(u, v)}
7          UNION(u, v)
8  return A

Correctness. When edge (u,v)(u, v) is accepted, let CC be the tree of the forest that contains uu. The cut (C,V∖C)(C, V \setminus C) respects AA, and (u,v)(u, v) crosses it. Every lighter edge crossing it was examined earlier and rejected, which only happens when its two ends were already in the same tree; but a crossing edge has its ends in different trees. So no lighter edge crosses the cut, (u,v)(u, v) is light, and by the corollary of the cut property it is safe. A rejected edge would close a cycle, which no tree contains. Since GG is connected, the final forest is one tree, an MST.

Watching it work

The Python version uses a disjoint-set forest with union by rank and path compression and prints each decision in the same order as the animation.

python · try it yourself
edges = [("A", "B", 4), ("A", "C", 3), ("B", "C", 2), ("B", "D", 5), ("C", "E", 7), ("D", "E", 6),
         ("D", "F", 9), ("E", "G", 8), ("F", "G", 10), ("F", "H", 1), ("G", "H", 11), ("E", "F", 12)]
V = "ABCDEFGH"

class DisjointSets:
    def __init__(self, items):
        self.p = {x: x for x in items}
        self.rank = {x: 0 for x in items}
    def find(self, x):
        root = x
        while self.p[root] != root:
            root = self.p[root]
        while self.p[x] != root:                   # path compression
            self.p[x], x = root, self.p[x]
        return root
    def union(self, a, b):
        a, b = self.find(a), self.find(b)
        if self.rank[a] < self.rank[b]:
            a, b = b, a
        self.p[b] = a
        if self.rank[a] == self.rank[b]:
            self.rank[a] += 1

def kruskal(V, edges):
    ds = DisjointSets(V)
    tree, total = [], 0
    for u, v, w in sorted(edges, key=lambda e: (e[2], e[0], e[1])):
        if ds.find(u) != ds.find(v):
            ds.union(u, v)
            tree.append((u, v, w)); total += w
            print(f"take {u}-{v} ({w:2}): tree weight {total}")
            if len(tree) == len(V) - 1:
                break
        else:
            print(f"skip {u}-{v} ({w:2}): {u} and {v} are already connected")
    return tree, total

tree, total = kruskal(V, edges)
print(f"MST: {len(tree)} edges, weight {total}")
take F-H ( 1): tree weight 1
take B-C ( 2): tree weight 3
take A-C ( 3): tree weight 6
skip A-B ( 4): A and B are already connected
take B-D ( 5): tree weight 11
take D-E ( 6): tree weight 17
skip C-E ( 7): C and E are already connected
take E-G ( 8): tree weight 25
take D-F ( 9): tree weight 34
MST: 7 edges, weight 34

AA-BB is rejected because BB-CC and AA-CC already joined AA and BB through CC, and CC-EE because C,B,D,EC, B, D, E are connected by then. After the seventh accepted edge the forest is a single tree and the loop stops; the heavier edges FF-GG, GG-HH and EE-FF are never looked at.

Running time

Line 2 makes VV sets. Sorting costs O(Elg⁡E)O(E \lg E). The loop does 2E2E FIND-SET and V−1V - 1 UNION operations; with union by rank and path compression they cost O((V+E) α(V))O((V + E)\,\alpha(V)) in total (why union-find is almost linear). Since GG is connected, E≥V−1E \ge V - 1, and α(V)=O(lg⁡V)\alpha(V) = O(\lg V), so the total is

O(Elg⁡E)=O(Elg⁡V)because E<V2 implies lg⁡E<2lg⁡VO(E \lg E) = O(E \lg V) \qquad \text{because } E < V^2 \text{ implies } \lg E < 2 \lg V

The sort dominates. If the weights are small integers, a counting or radix sort makes the sort linear, and Kruskal runs in O(E α(V))O(E\,\alpha(V)) time. The program counts both kinds of work on random graphs: comparisons made by the sort and parent pointers followed by the finds.

python · try it yourself
import random

class Counting:
    comparisons = 0
    def __init__(self, w): self.w = w
    def __lt__(self, other):
        Counting.comparisons += 1
        return self.w < other.w

def kruskal_cost(n, edges):
    Counting.comparisons = 0
    order = sorted(edges, key=lambda e: Counting(e[2]))
    p, rank, steps = list(range(n)), [0] * n, 0
    def find(x):
        nonlocal steps
        root = x
        while p[root] != root:
            root = p[root]; steps += 1
        while p[x] != root:
            p[x], x = root, p[x]
        return root
    taken = 0
    for u, v, w in order:
        a, b = find(u), find(v)
        if a != b:
            if rank[a] < rank[b]: a, b = b, a
            p[b] = a
            rank[a] += rank[a] == rank[b]
            taken += 1
    return Counting.comparisons, steps, taken

rng = random.Random(9)
print(f"{'V':>6} {'E':>7} {'sort comparisons':>17} {'find steps':>11} {'tree edges':>11}")
for n in [100, 400, 1600, 6400]:
    edges = [(i, i + 1, rng.randint(1, 10 ** 6)) for i in range(n - 1)]       # a path keeps it connected
    edges += [(rng.randrange(n), rng.randrange(n), rng.randint(1, 10 ** 6)) for _ in range(4 * n)]
    c, s, t = kruskal_cost(n, edges)
    print(f"{n:>6} {len(edges):>7} {c:>17,} {s:>11,} {t:>11}")
     V       E  sort comparisons  find steps  tree edges
   100     499             3,827         926          99
   400    1999            19,319       3,797         399
  1600    7999            93,286      15,220        1599
  6400   31999           436,971      61,087        6399

The sort makes about Elg⁡EE \lg E comparisons, while all the finds together follow about two parent pointers per edge: union-find is nearly free here.

In C++

The C++ version sorts an edge array with std::sort and uses a compact disjoint-set structure.

cpp · try it yourself
#include <algorithm>
#include <cstdio>
#include <numeric>
#include <tuple>
#include <vector>

struct DSU {
    std::vector<int> p, rank;
    explicit DSU(int n) : p(n), rank(n, 0) { std::iota(p.begin(), p.end(), 0); }
    int find(int x) {
        int root = x;
        while (p[root] != root) root = p[root];
        while (p[x] != root) { int next = p[x]; p[x] = root; x = next; }
        return root;
    }
    bool unite(int a, int b) {
        a = find(a); b = find(b);
        if (a == b) return false;
        if (rank[a] < rank[b]) std::swap(a, b);
        p[b] = a;
        if (rank[a] == rank[b]) ++rank[a];
        return true;
    }
};

int main() {
    std::vector<std::tuple<int, char, char>> edges = {               // (weight, u, v)
        {4, 'A', 'B'}, {3, 'A', 'C'}, {2, 'B', 'C'}, {5, 'B', 'D'}, {7, 'C', 'E'}, {6, 'D', 'E'},
        {9, 'D', 'F'}, {8, 'E', 'G'}, {10, 'F', 'G'}, {1, 'F', 'H'}, {11, 'G', 'H'}, {12, 'E', 'F'}};
    std::sort(edges.begin(), edges.end());
    DSU ds(8);
    int total = 0, taken = 0;
    for (auto [w, u, v] : edges) {
        if (ds.unite(u - 'A', v - 'A')) {
            total += w;
            std::printf("take %c-%c (%d)\n", u, v, w);
            if (++taken == 7) break;
        }
    }
    std::printf("MST weight %d\n", total);
}
take F-H (1)
take B-C (2)
take A-C (3)
take B-D (5)
take D-E (6)
take E-G (8)
take D-F (9)
MST weight 34

Clustering: stopping early

Stop Kruskal's algorithm when kk trees remain instead of one, and the trees are kk clusters with the largest possible spacing, the minimum distance between points in different clusters. The next edge Kruskal would accept is exactly that spacing. The program clusters 12 points on a grid, using squared Euclidean distances as weights.

python · try it yourself
points = {"a": (0, 0), "b": (1, 1), "c": (0, 2), "d": (2, 0), "e": (8, 1), "f": (9, 0),
          "g": (9, 2), "h": (4, 8), "i": (5, 9), "j": (3, 9), "k": (5, 7), "l": (10, 9)}
names = sorted(points)
edges = sorted(((points[u][0] - points[v][0]) ** 2 + (points[u][1] - points[v][1]) ** 2, u, v)
               for i, u in enumerate(names) for v in names[i + 1:])

def clusters(k):
    p = {x: x for x in names}
    def find(x):
        while p[x] != x:
            p[x] = p[p[x]]                      # path halving
            x = p[x]
        return x
    count = len(names)
    for w, u, v in edges:
        a, b = find(u), find(v)
        if a == b:
            continue
        if count == k:
            groups = {}
            for x in names:
                groups.setdefault(find(x), []).append(x)
            return sorted("".join(g) for g in groups.values()), w
        p[a] = b
        count -= 1

for k in [4, 3, 2]:
    groups, spacing = clusters(k)
    print(f"k = {k}: {groups}, spacing (squared) = {spacing}")
k = 4: ['abcd', 'efg', 'hijk', 'l'], spacing (squared) = 25
k = 3: ['abcd', 'efg', 'hijkl'], spacing (squared) = 37
k = 2: ['abcdefg', 'hijkl'], spacing (squared) = 41

The far point ll is a cluster of its own for k=4k = 4 and joins {h,i,j,k}\{h, i, j, k\} for k=3k = 3, through its squared distance 25 to ii. At each kk the printed spacing is the weight of the edge Kruskal would accept next, and no other split into kk clusters has a larger one. Practise with Minimum Spanning Tree, which asks for the MST weight, and Components After Each Union, which is Kruskal's bookkeeping on its own.

Test yourself

Kruskal examines edge (u,v)(u, v) and finds FIND-SET(u)(u) = FIND-SET(v)(v). What does it do, and why?

  1. Takes the edge, because it is light
  2. Skips it, because uu and vv are already in one tree and the edge would close a cycle
  3. Replaces the heaviest edge of the tree
  4. Stops

What dominates Kruskal's running time with a disjoint-set forest?

  1. The union operations
  2. Sorting the edges, O(Elg⁡E)O(E \lg E)
  3. MAKE-SET
  4. Checking connectivity at the end

Why is O(Elg⁡E)O(E \lg E) the same as O(Elg⁡V)O(E \lg V)?

  1. Because E=VE = V
  2. Because E<V2E < V^2, so lg⁡E<2lg⁡V\lg E < 2 \lg V
  3. Because sorting is linear
  4. It is not