110 likes | 198 Views
Algorithm design minimum Spanning Trees. Dr. O.Bushehrian. A spanning tree for G is a connected subgraph that contains all the vertices in G and is a tree. 2. Y. 1. 6. 2. 1. Y. 1. 6. 3. 3. 3. 4. 4. 4. 2. 3. 1. 1. 5. 4. 5. 1.
E N D
Algorithm designminimum Spanning Trees Dr. O.Bushehrian
A spanning treefor G is a connected subgraph that contains all the vertices in G and is a tree.
2 Y 1 6 2 1 Y 1 6 3 3 3 4 4 4 2 3 1 1 5 4 5 1 فاصله گره 5 از مجموعه Y: min(4,3)=3 Distance[5]=3, nearest[5]=2 Distance[4]=1, nearest[4]=3 فاصله گره 4 از مجموعه Y: min(1,2)=1
A weighted graph and the steps in Prim's algorithm for that graph
The array representation W of the graph W[i][J] = weight on edge if there is an edge between vi and vJ ∞ if there is no edge between vi and vJ 0 if i=J
Prim's Algorithm: nearest [i] =index of the vertex in Y nearest to vi distance [i] = weight on edge between vi and the vertex indexed by nearest [i] void prim (intn, number W[] [] ) { index i, vnear; number min; edge e; index nearest [2 . . n]; number distance [2 . . n]; F = Ø; for (i = 2; i <= n; i++){ nearest [i] = 1; distance [i] = W[1] [i] ; }
repeat (n - 1 times){ min = ∞ for (i = 2; i <= n; i++) { if (0 ≤ distance [i] < min) { min = distance [i]; vnear = i; } } e = edge connecting vertices indexed by vnear and nearest [vnear]; add e to F; distance [vnear] = - 1; for (i = 2; i <= n; i++) { if (W[i] [vnear] < distance [i]){ distance = W[i] [vnear]; nearest [i] = vnear; } } } } T(n) = 2 (n - 1) (n - 1) ∊ Θ (n2).
Kruskal'sAlgorithm weighted graph and the steps in Kruskal's algorithm for that graph.
void kruskal (int n, intm, set_of_edges E, set_of_edgesF) { index i, j; set_pointer p, q; edge e; Sort the m edges in E by weight in nondecreasing order; F = Ø; while (number of edges in F is less than n - 1){ e = edge with least weight not yet considered; i, j = indices of vertices connected by e; p = find(i); q = find(j); if (! equal(p, q)){ merge(p, q); add e to F; } } }
Analysis of Krukal's Algorithm Worst-case Time-Complexity W ( m, n ) €Ѳ ( m log m) m = n (n-1) / 2 €Ѳ ( n2 ) W ( m, n ) €Ѳ(n2log n2) = Ѳ (n22 log n) = Ѳ (n2 log n)
Comparing Prim's Algorithm with Kruskal'sAlgorithm Prim's Algorithm: T(n) ∊ θ(n2) Kruskal's Algorithm: W (m, n) ∊ θ(mlgm) and W (m, n) ∊ θ (n2lgn) in a connected graph: n-1 <= m <= n (n-1) /2 For a graph whose number of edges m is near the low end of these limits (the graph is very sparse), Kruskal's algorithm is θ(n lg n), which means that Kruskal's algorithm should be faster. However, for a graph whose number of edges is near the high end (the graph is highly connected), Kruskal's algorithm is θ (n2 lg n), which means that Prim's algorithm should be faster.