Beruflich Dokumente
Kultur Dokumente
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);
}
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:
OUTPUT:
Enter no. of vertices:6
031000
300030
100004
000002
030000
004200
Page | 52