Prim's algorithm
◈ 4 cardsGrow one tree from a root using a min-priority queue keyed by the lightest edge to the tree. Vertex-centric, O(E lg V).
Prim: grow a single tree
Where Kruskal manages many components, Prim grows one tree outward from a root . Every non-tree vertex carries two attributes: v.key = the weight of the lightest edge connecting to the current tree (initially , with r.key = 0), and v.π = the tree endpoint of that edge.
Keep all vertices in a min-priority queue ordered by key. Repeat until is empty:
u = EXTRACT-MIN(Q)— pull out the non-tree vertex with the lightest connecting edge; this commits the edge to the MST.- For each neighbor of still in : if , set
v.key = w(u,v),v.π = u, andDECREASE-KEY(Q, v, w(u,v)).
Running time. EXTRACT-MINs and up to DECREASE-KEYs. With a binary min-heap each is , giving . A Fibonacci heap makes DECREASE-KEY amortized, improving the bound to — better for dense graphs.
Why it is correct
At each step the cut is (vertices already in the tree) versus . Every -edge lies inside , so the cut respects . EXTRACT-MIN returns the vertex whose connecting edge is the light edge crossing , so by Corollary 21.2 the committed edge is safe. This is the same proof skeleton as Dijkstra — extract the minimum-key vertex, then relax its neighbors. Prim and Dijkstra differ only in the key formula: Prim uses (edge weight to the tree); Dijkstra uses (cumulative distance from the source).
Worked example
Running Prim from vertex 0 on the same CLRS Fig 21.4 graph chooses a different set of edges than Kruskal in general, but the total is identical: 37. (An MST's weight is unique even when the tree is not.)