Sie sind auf Seite 1von 5

LAB – 8

AIM:
To generate a minimum cost spanning tree using the Kruskal’s algorithm.

SOFTWARE USED:
Ubuntu 16.04 in VM Virtual Box.

PSEUDOCODE:
kruskalAlgo(E, cost, n, t){
construct a min heap out of edges cost
for i = 1 to n do
print[i] = -1
i = 0, mincost = 0;
while(i <= n-1 and (heap not empty))
delete a mincost edge
(u,v) from the heap and reheapify rest
j = find(u)
k = find(v)
if(j != k) then{
i=i+1
t[i, 1] = u, t[i, 2] = v
mincost = mincost + cost(u, v)
union(j, k)
}
} end while
if(i != n-1) then no MST
else mincost

Page | 48
algoUnion(i, j){
p[i] = j
}

algoFind(i){
while(p[i] >= 0) do i = p[i]
return i
}

SOURCE CODE:
#include<stdio.h>
#include<stdlib.h>

int i,j,k,a,b,u,v,n,ne=1;
int min,mincost=0,cost[9][9],parent[9];
int find(int);
int uni(int,int);
void main(){
printf("Enter the no. of vertices\n");
scanf("%d",&n);
printf("Enter the adjacency matrix\n");
for(i=1;i<=n;i++){
for(j=1;j<=n;j++){
scanf("%d",&cost[i][j]);
if(cost[i][j]==0)
cost[i][j]=999;

Page | 49
}
}
printf("The edges of Minimum Cost Spanning Tree are\n");
while(ne<n){
for(i=1,min=999;i<=n;i++){
for(j=1;j<=n;j++){
if(cost[i][j]<min){
min=cost[i][j];
a=u=i;
b=v=j;
}
}
}
u=find(u);
v=find(v);
if(uni(u,v)){
printf("%d edge (%d,%d) =%d",ne++,a,b,min);
mincost +=min;
}
cost[a][b]=cost[b][a]=999;
}
printf("Minimum cost = %d",mincost);
}

int find(int i){


while(parent[i])
i=parent[i];
return i;
}

Page | 50
int uni(int i,int j){
if(i!=j){
parent[j]=i;
return 1;
}
return 0;
}

ANALYSIS:
Kruskal's algorithm can be shown to run in O(E log E) time, or equivalently, O(E log V) time,
where E is the number of edges in the graph and V is the number of vertices, all with
simple data structures. These running times are equivalent because:

 E is at most V2 and log V2 = 2log V is O(log V).


 Each isolated vertex is a separate component of the minimum spanning forest. If
we ignore isolated vertices we obtain V ≤ 2E, so log V is O(log E).
We can achieve this bound as follows: first sort the edges by weight using a comparison
sort in O(E log E) time; this allows the step "remove an edge with minimum weight from
S" to operate in constant time. Next, we use a disjoint-set data structure to keep track of
which vertices are in which components. We need to perform O(V) operations, as in each
iteration we connect a vertex to the spanning tree, two 'find' operations and possibly one
union for each edge. Even a simple disjoint-set data structure such as disjoint-set forests
with union by rank can perform O(V) operations in O(V log V) time. Thus the total time is
O(E log E) = O(E log V).

OUTPUT:
Enter no. of vertices:6

Enter the adjacency matrix:


031600
305030
150564
605002
Page | 51
036006
004260

spanning tree matrix:

031000
300030
100004
000002
030000
004200

Total cost of spanning tree = 13

Page | 52

Das könnte Ihnen auch gefallen