

Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!


Kruskal's algorithm: sort the edges of G in increasing order by length keep a subgraph S of G, initially empty for each edge e in sorted order if the endpoints of e are disconnected in S add e to S return S Note that, whenever you add an edge (u,v), it's always the smallest connecting the part of S reachable from u with the rest of G, so by the lemma it must be part of the MST. example void kruskal (vertex-set V; edge-set E; edge-set T) int ncomp; /* current number of components / priority-queue edges / partially ordered tree / mfset components; / merge-find set data structure / vertex u, v; edge e; int nextcomp; / name for new component / int ucomp, vcomp; / component names / { makenull (T); makenull (edges); nextcomp = 0; ncomp = n; for (v$ \in$V) / initialize a component to have one vertex of V/ { nextcomp++ ; initial (nextcomp, v, components); } for (e$ \in$E) insert (e, edges); / initialize priority queue of edges */ while (ncomp > 1) { e = deletemin (edges); let e = (u, v); ucomp = find(u, components); vcomp = find(v, components); if (ucomp! = vcomp)
merge (ucomp, vcomp, components); ncomp = ncomp - 1; } } }
Prim's algorithm: let T be a single vertex x while (T has fewer than n vertices) { find the smallest edge connecting T to G-T add it to T } Since each edge added is the smallest connecting T to G-T, the lemma we proved shows that we only add edges that should be part of the MST. Again, it looks like the loop has a slow step in it. But again, some data structures can be used to speed this up. The idea is to use a heap to remember, for each vertex, the smallest edge connecting T with that vertex. Prim with heaps: make a heap of values (vertex,edge,weight(edge)) initially (v,-,infinity) for each vertex let tree T be empty while (T has fewer than n vertices) { let (v,e,weight(e)) have the smallest weight in the heap remove (v,e,weight(e)) from the heap add v and e to T for each edge f=(u,v) if u is not already in T find value (u,g,weight(g)) in heap if weight(f) < weight(g) replace (u,g,weight(g)) with (u,f,weight(f)) }