Ada Kruskal

You might also like

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 8

Program to find the minimum cost spanning tree using Kruskal’s algorithm and

estimate the time and space complexity


Step-1: Algorithm Design

Algorithm : MST-KRUSKAL’S

Input- n: no of nodes, cost: nXn adjacency matrix of the input graph

Output- edges of the minimum spanning tree, mincost: minimum cost

Algorithm Time Frequency


Main()
Begin
Ne=1 1 1
Mincost=0 1 1
For i=1 to n do 3 N+1
For j=1 to n do 3 N*(N+1)
If cost[i][j]=0 2 N*N
Cost[i][j]=999 2 1
End if
End for
End for
While(ne<n) do 1 N+1
Min=999 1 N
For i=1 to n do 3 N*(N+1)
For j=1 to n do 3 N*N*(N+1)
If(cost[i][j]<min) 2 N*N*N
Then
Min=cost[i][j] 2 1
A=u=i 2 1
B=v=j 2 1
End if
End for
End for
End while
U=find(u) 2 1
V=find(v) 2 1
If(uni(u,v)) 1 1
Then
Mincost+=min 2 1
End if
Cost[a][b]=cost[b][a]=999 4 1

End begin

Find(i)
Begin
While(parent[i]) do 1 N+1
I=parent[i] 2 N
End while
End begin

Uni(I,j)
Begin
If(i!=j) 1 1
Then
Parent[j]=i 2 1
End if
End begin

Step: 2 :Apriori Analysis

Totaltime=1+1+3*(N+1)+3*(N*(N+1))+2*(N*N)+2+N+1+N+3*(N*(N+1))+3*(N*N*(N+1))

+2*(N*N*N)+2+2+2+2+2+1+2+4+N+1+2N+1+2

=5N3+9N2+16N+29

Table: n vs T
n Total Time(T)
4 877
5 959
6 1529
8 3293
9 4547
Graph:

Apriori Analysis
5000
4500
4000
3500
Axis Title

3000
2500
2000 Series1
1500
1000
500
0
1 2 3 4 5
Axis Title

Step 3:

//KRUSKAL'S ALGORITHM

#include<stdio.h>

#include<conio.h>

#include<stdlib.h>

int i,j,k,a,b,u,v,n,ne=1;

int min,mincost=0,cost[10][10],parent[10],t=4;

int find(int i)

t=t+1;

while(parent[i])

i=parent[i];
t=t+2;

return i;

int uni(int i,int j)

t=t+1;

if(i!=j)

parent[j]=i;

t=t+2;

return 1;

return 0;

void main()

clrscr();

printf("\nImplementation of KRUSKAL's ALGORITHM\n\n");

printf("\nEnter number of vertices\n");

scanf("%d",&n);
printf("\nEnter the cost adjacency matrix\n");

t=t+1;

for(i=1;i<=n;i++)

t=t+2;

for(j=1;j<=n;j++)

t=t+3;

scanf("%d",&cost[i][j]);

t=t+2;

if(cost[i][j]==0)

cost[i][j]=999;

t=t+2;

printf("\nThe edges of Minimum cost spanning tree are:\n");

t=t+1;

while(ne<n)
{

t=t+2;

for(i=1,min=999;i<=n;i++)

t=t+2;

for(j=1;j<=n;j++)

t=t+3;

if(cost[i][j]<min)

t=t+2;

min=cost[i][j];

t=t+2;

a=u=i;

t=t+2;

b=v=j;

t=t+2;

}
u=find(u);

t=t+2;

v=find(v);

t=t+3;

if(uni(u,v))

printf("\n%d Edge (%d,%d)=%d\n",ne++,a,b,min);

mincost+=min;

t=t+2;

cost[a][b]=cost[b][a]=999;

t=t+4;

printf("\n\nMinimum cost=%d\n",mincost);

printf("\nTime complexity=%d\n",t);

printf(“\nSpace complexity=%d\n”, sizeof(a)+ sizeof(b)+ sizeof(u)+ sizeof(v)+


sizeof(n)+ sizeof(min)+ sizeof(cost)+ sizeof(parent));

getch();

}
Step 4: Aposteriori analysis:

n t
4
5
6
8
9

You might also like