dr. o.bushehrian algorithm design minimum spanning trees
TRANSCRIPT
گره مجموعه 5فاصله :Yازmin(4,3)=3
Distance[5]=3, nearest[5]=2
گره مجموعه 4فاصله :Yازmin(1,2)=1
Distance[4]=1, nearest[4]=3
1 2
3
6Y
5
24 3
1 4
1
1 2
3
6Y
5
43
1
4
1
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 (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] ;}
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).
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; } }}
Analysis of Krukal's Algorithm Worst-case Time-Complexity
W ( m, n ) € Ѳ ( m log m)
m = n (n-1) / 2 € Ѳ ( n2 )
W ( m, n ) € Ѳ (n2 log n2) = Ѳ (n2 2 log n) = Ѳ (n2 log n )
Comparing Prim's Algorithm with Kruskal's Algorithm
Prim's Algorithm: T(n) ∊ θ(n2)
Kruskal's Algorithm: W (m, n) ∊ θ(m lg m) and W (m, n) ∊ θ (n2 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.