Download presentation
Presentation is loading. Please wait.
Published byMoris Roland Nash Modified over 9 years ago
1
Dr. O.Bushehrian ALGORITHM DESIGN MINIMUM SPANNING TREES
2
A spanning tree for G is a connected subgraph that contains all the vertices in G and is a tree.
3
فاصله گره 5 از مجموعه Y: min(4,3)=3 Distance[5]=3, nearest[5]=2 فاصله گره 4 از مجموعه Y: min(1,2)=1Distance[4]=1, nearest[4]=3 1 2 3 6 Y 5 24 3 1 4 1 1 2 3 6 Y 5 4 3 1 4 1
4
A weighted graph and the steps in Prim's algorithm for that graph
5
The array representation W of the graph W[i][J] = weight on edge if there is an edge between v i and v J ∞ if there is no edge between v i and v J 0 if i=J
6
Prim's Algorithm: nearest [i] =index of the vertex in Y nearest to v i distance [i] = weight on edge between v i and the vertex indexed by nearest [i] void prim (int n, 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] ; }
7
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) ∊ Θ (n 2 ).
8
Kruskal's Algorithm weighted graph and the steps in Kruskal's algorithm for that graph.
9
void kruskal (int n, int m, set_of_edges E, set_of_edges F) { 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; } } }
10
Analysis of Krukal's Algorithm Worst-case Time-Complexity W ( m, n ) € Ѳ ( m log m) m = n (n-1) / 2 € Ѳ ( n 2 ) W ( m, n ) € Ѳ (n 2 log n 2 ) = Ѳ (n 2 2 log n) = Ѳ (n 2 log n )
11
Comparing Prim's Algorithm with Kruskal's Algorithm Prim's Algorithm: T(n) ∊ θ (n 2 ) Kruskal's Algorithm: W (m, n) ∊ θ (m lg m) and W (m, n) ∊ θ (n 2 lg n) 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.
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.