Experiment Number 09 DAA
Experiment Number 09 DAA
Program Name:
Write a program in C to find Minimum Spanning Tree using Kruskal’s Algorithm.
Theory Concept:
Kruskal's Algorithm is used to find the Minimum Spanning Tree (MST) of a graph. The
algorithm does the following:
1. Sorts all edges in non-decreasing order of their weights.
2. Picks the smallest edge, ensuring that adding it to the MST does not form a cycle.
3. Repeats until all vertices are connected.
The algorithm uses the Union-Find data structure for cycle detection.
Implementation :
#include <stdio.h>
#include <stdlib.h>
// Structure to represent an edge
typedef struct {
int src, dest, weight;
} Edge;
// Function to find the parent of a vertex
int findParent(int parent[], int v) {
if (parent[v] == v)
return v;
return findParent(parent, parent[v]);
}
// Function to perform union of two subsets
void unionSets(int parent[], int rank[], int x, int y) {
int rootX = findParent(parent, x);
int rootY = findParent(parent, y);
if (rank[rootX] < rank[rootY])
parent[rootX] = rootY;
else if (rank[rootX] > rank[rootY])
parent[rootY] = rootX;
else {
parent[rootY] = rootX;
rank[rootX]++;
}
}
// Function to sort edges by weight
void sortEdges(Edge edges[], int E) {
for (int i = 0; i < E - 1; i++) {
for (int j = 0; j < E - i - 1; j++) {
if (edges[j].weight > edges[j + 1].weight) {
Edge temp = edges[j];
edges[j] = edges[j + 1];
edges[j + 1] = temp;
}
}
}
}
// Function to find MST using Kruskal's Algorithm
void kruskalMST(Edge edges[], int V, int E) {
int parent[V], rank[V];
for (int i = 0; i < V; i++) {
parent[i] = i;
rank[i] = 0;
}
sortEdges(edges, E);
printf("Edges in the Minimum Spanning Tree:\n");
int totalWeight = 0, edgeCount = 0;
for (int i = 0; i < E && edgeCount < V - 1; i++) {
int x = findParent(parent, edges[i].src);
int y = findParent(parent, edges[i].dest);
if (x != y) {
printf("%d -- %d == %d\n", edges[i].src, edges[i].dest, edges[i].weight);
totalWeight += edges[i].weight;
edgeCount++;
unionSets(parent, rank, x, y);
}
}
printf("Total weight of MST: %d\n", totalWeight);
}
int main() {
int V, E;
printf("Enter the number of vertices: ");
scanf("%d", &V);
printf("Enter the number of edges: ");
scanf("%d", &E);
Edge edges[E];
printf("Enter each edge (src, dest, weight):\n");
for (int i = 0; i < E; i++) {
printf("Edge %d: ", i + 1);
scanf("%d %d %d", &edges[i].src, &edges[i].dest, &edges[i].weight);
}
kruskalMST(edges, V, E);
return 0;
}
Output:
Enter the number of vertices: 4
Enter the number of edges: 5
Enter each edge (src, dest, weight):
Edge 1: 0 1 10
Edge 2: 0 2 6
Edge 3: 0 3 5
Edge 4: 1 3 15
Edge 5: 2 3 4