Professional Documents
Culture Documents
Implementation of Kruskal'S Method For A Graph
Implementation of Kruskal'S Method For A Graph
FOR A GRAPH
Assistant Professor
1
Table of Contents
1 Aim 3
2 Objective 3
3 Strategy 3
4 Introduction 3
5 Definition 3
6 Algorithm 4
7 Program 5-7
8 Output 8
2
Aim: Implementation of Kruskal’ method for a graph using c .
Introduction: This paper presents a theoretical study on Kruskal’ minimum spanning tree
algorithm. This minimum spanning tree algorithm was first described by Joseph B. Kruskal, Jr in
1956 in his paper published by Proceedings of American Mathematical society. The algorithm
was again rediscovered in 1957 by Loberman and Weinberger.
Definition:
Kruskal's algorithm is a greedy algorithm in graph theory that finds a minimum spanning tree
for a connected weighted graph.
3
It finds a subset of the edges that forms a tree that includes every vertex, where the total
weight of all the edges in the tree is minimized.
This algorithm is directly based on the MST( minimum spanning tree) property.
Kruskal’s Algorithm:
1. MST-KRUSKAL(G, w)
2. A ←Ø
3. for each vertex v V[G]
4. do MAKE-SET(v)
5. sort the edges of E into non decreasing order by weight w
6. for each edge (u, v) E, taken in non decreasing order by
weight
7. doif FIND-SET(u)≠ FIND-SET(v)
8. then A ← A {(u, v)}
9. UNION(u, v)
10. return A
4
PROGRAM:
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
inti,j,k,a,b,u,v,n,ne=1;
intmin,mincost=0,cost[9][9],parent[9];
int find(int);
intuni(int,int);
int main()
scanf("%d",&n);
for(i=1;i<=n;i++)
5
for(j=1;j<=n;j++)
scanf("%d",&cost[i][j]);
if(cost[i][j]==0)
cost[i][j]=999;
while(ne < n)
for(i=1,min=999;i<=n;i++)
min=cost[i][j];
a=u=i;
b=v=j;
u=find(u);
6
v=find(v);
if(uni(u,v))
mincost +=min;
cost[a][b]=cost[b][a]=999;
getch();
int find(int i)
while(parent[i])
i=parent[i];
return i;
intuni(inti,int j)
if(i!=j)
parent[j]=i;
return 1;
7
}
return 0;
OUTPUT:
8
9