Kruskal Alg
Kruskal Alg
vertices.
// cost is an array storing edge (p,g).
tree.
/tree contains the edges of minimum-cost spanning
holdss the minimum cost of spanning tree
/min
while (i<n-1)
i:=i+1
tree [i, 1]:=p;
tree [i, 2] :=q:
min:=min+cost [p,q);
Union (s,t); //merge S and t
// cost is an
array storing edge (p,
/ tree contains the edges of
q).
minimum-cost spanning tree
min holds the minimum cost of
spanning tree.
while (isn-1)
i:=i+l;
tree[i, 1] :=p;
tree[i, 2] :=q;
min:=min+cost [p, ql;
Union (s,t); //merge s and t
30
-O
3
25
10
20
(4
2 12
15
20
5
5
1,2=10
1 ,31 =
1,5=
1 ,61= 0
1 , 71 =
Now
1, 2 31 = 30
1, 2, 41
1,2, 71 =
1,2, 5} =
1,2, 6} = oo
Desig
Hence select 3.
S[3= 1
Now
1, 2, 3, 4 = 45
1, 2, 3, 5 = 35
11, 2, 3, 6) =
1, 2, 3, 71 = o
S[5 = 1
Now
1, 2, 3, 5, 6} =
1, 2, 3, 5, 71 = 42
Hence vertex 7 will be selected. In single source shortest path if destination vertex
is7 then we have achieved shortest path 1 2 3 5 - 7 with path length 42. The
single source shortest path from each vertex is summerised below
1, 2 10
1, 2, 3 30
1, 2. 3, 4 45
1, 2, 3, 5 35
1, 2. 3, 4,7 65
1. 2, 3, 5, 7 42
1, 6 30
1.67 65
3.5.1 Algorithm
The algorithm for single source shortest path is given as
Algorithm Sh _Fath ( P,cost, Dist,n)
/7type arraY.
//initially
for i : =1 to n do
Sil:=0;
Dist:= Cost Ip, i];
th
SIp]:=l // set vertex to true in array S and 1.e. put p ir
Dist [p) : =0.0;
for val:=2 to n-2 doo
3.5.2 Analysis
Time Complexity of the
algorithm:
The 1st for-loop clearly takes O(n) time
Choosing q takes O(n) time, because it involves
array.
finding a minimum in an
The innermost for-loop for updating Dist iterates at most n times, thus takes
O(n) time.
Therefore, the for-loop iterating over val takes
Thus, single source shortest
O(n*n) time
path takes O(n) time.