Card 06/ 09

ComparisonDifficulty: Intermediate2 min

Kruskal vs Prim

Kruskal's sorts every edge and suits sparse graphs; Prim's grows from a vertex and suits dense ones.

Kruskal's algorithm and Prim's algorithm both find a minimum spanning tree, and the choice between them comes down to how the graph is stored and how many edges it has. This card sets out what they share, where they differ, and a rule for picking one.

Both are greedy: each adds one edge at a time and never takes one back. Both are correct for the same reason, the cut property from Minimum Spanning Trees and the Cut Property, applied to a different cut at each step. On the topic's graph both found the tree A-C, B-C, B-D, D-E, E-F with total 17, and when no two weights are equal they always find the same tree, because there is only one. They differ in what they grow, what they need, and what they cost.

Kruskal's algorithm and Prim's algorithm side by side, on a graph of V vertices and E edges
AspectKruskal's algorithmPrim's algorithm
What it growsA forest of trees that mergeOne tree from a start vertex
Each step addsThe lightest edge anywhere that joins two treesThe lightest edge leaving the tree
NeedsThe edges sorted, and union-findA priority queue, or a best edge per vertex
TimeO(E log E) for the sortO(E log V) with a heap; O(V²) with a scan
Order on the topic's graphA-C, B-C, D-E, B-D, E-FA-C, B-C, B-D, D-E, E-F from A
Input it suitsA list of edgesLists of neighbours, or a matrix of weights
On a disconnected graphA minimum spanning forest, one tree per partA tree over the start's part only

The two heap-based times are closer than they look. E is at most V², so log E is at most 2 log V, and O(E log E) is the same class as O(E log V). What separates them in practice is the input: Kruskal's algorithm has to see every edge before it starts, while Prim's works outward from what it has. On a dense graph, where E is close to V², Prim's algorithm with a plain scan of best edges runs in O(V²) and beats both heap versions, since it never sorts or pushes an edge at all.

The rule: use Kruskal's algorithm when the edges come as a list or the graph is sparse, and when a forest is an acceptable answer; use Prim's algorithm when the graph is dense, stored as neighbours or a matrix, or when the tree must grow from a given vertex.