Prim's Algorithm How does Prim's algorithm work? 1. Start with a single arbitrary node. 2. Repeatedly add the smallest weight edge that connects a node in the tree with a node not in the tree. How do you find the smallest weight edge? use two arrays d[] and e[] indexed by node (d[] stores edge weights, e[] stores edges) mark nodes that are in the tree (or use a set) Prim's Algorithm Example Use Prim's algorithm to find a minimal spanning tree. For each iteration, give the node and edge added to the tree, along with the contents of the d[] and e[] arrays. Use 'San Francisco' as the initial node. (graph16.pdf) $35 Atlanta Chicago $70 Atlanta Denver $40 Atlanta New York $65 Chicago Denver $50 Chicago New York $60 Chicago San Francisco $45 Denver San Francisco S---C---N \ / \ / D---A Classwork You may work with a partner. Use Prim's algorithm to find a minimal spanning tree. For each iteration, give the node and edge added to the tree, along with the contents of the d[] and e[] arrays. Use 'a' as the initial node. (graph17.pdf) V = { a, b, c, d, e, f } E = { {a,b}, {a,d}, {b,c}, {b,d}, {b,f}, {c,f}, {d,e}, {e,f} } Use these edge weights. {a,b} 8 {a,d} 11 {b,c} 7 {b,d} 6 {b,f} 4 {c,f} 14 {d,e} 1 {e,f} 2 a---b---c | / \ | d---e---f Prim's Algorithm Code Prim(Node x) initialize the set of edges T to be empty initialize the array d[] to infinity for each node repeat n-1 times (add n-1 edges to the tree) mark node x for each node y that is adjacent to node x w = weight on edge {x,y} if (y is not marked and w < d[y]) d[y] = w e[y] = {x,y} end if end for set node x to the unmarked node with smallest d[] value get the edge {a,b} for node x from array e[] and add to T end repeat T contains the edges in the tree end Prim What's the Big-Oh for the running time of Prim's Algorithm? 1. The main loop repeats O(n) times. 2. Updating arrays is O(e) over all iterations of the main loop. 3. Finding the node with smallest distance is O(n). 4. Prim is O(n^2 + e) which is O(n^2) (since e <= n^2) Greedy Algorithms What's a Greedy Algorithm? 1. Makes a series of decisions. 2. At each step makes a greedy choice (best at the time). How are Kruskal's and Prim's Algorithms examples of Greedy Algorithms? Both choose the smallest weight edge at each step.