Growing a minimum spanning tree
1 | GENERIC_MST(G, w) |
Safe-Edge Theorem
Let G = (V, E) be a connected, undirected graph with a real-valued weight function w defined on E. Let A be a subset of E that is inclueded in some minimum spanning tree for G, let (S, V-S) be any cut of G that
respects A, and let (u,v) be a light edge crossing (S, V-S). Then edge(u, v) is safe for A.
Kruskal
1 | MST-KRUSKAL(G, w) |
The operation FIND-SET(u) returns a representative element from the set that contains u. Thus, we can determine whether two vertices u and v belong to the same tree by testing whether FIND-SET(u) equals FIND-SET(v). To combine trees, Kruskal’s algorithm calls the UNION procedure.
Lines 1–3 initialize the set A to the empty set and create |V| trees, one containing each vertex. The for loop in lines 5–8 examines edges in order of weight, from lowest to highest. The loop checks, for each edge (u, v), whether the endpoints u and v belong to the same tree. If they do, then the edge (u, v) cannot be added to the forest without creating a cycle, and the edge is discarded. Otherwise, the two vertices belong to different trees. In this case, line 7 adds the edge (u, v) to A, and line 8 merges the vertices in the two trees.
Running Time: O(ElgV)
Prim
1 | MST-PRIM(G, W, r) |
The running time of Prim’s algorithm depends on how we implement the minpriority queue Q.
If we implement Q as a binary min-heap, the total time for Prim’s algorithm is O(ElgV), which is
asymptotically the same as for our implementation of Kruskal’s algorithm.
if we use a Fibonacci heap to implement the min-priority queue Q, the running time of Prim’s
algorithm improves to O(E + VlgV)