_DAA Exp5.1
_DAA Exp5.1
UID: 2023300242
AIM: Experiment on Graphs: To understand Graphs and implement Prim’s and Kruskal’s
Algorithm to find Minimum Spanning Trees.
Program 1
Theory:
Kruskal’s Algorithm:
Kruskal’s algorithm sorts all edges by weight and greedily picks the smallest edge
that does not form a cycle, using the Union-Find data structure to manage
connected components.
Always pick the smallest edge first, which helps in building the Minimum
Spanning Tree (MST) optimally.
We use the Union-Find data structure to efficiently check whether two nodes
belong to the same set (connected component).
If u and v belong to different sets, we merge them (union) and add the edge to
the MST.
If they are already in the same set, we skip the edge to avoid a cycle.
Step 4: Repeat Until We Get (V-1) Edges
The MST must have exactly (V-1) edges, where V is the number of vertices.
Once we reach this count, the MST is complete, and we stop adding edges.
Problem: Kruskal’s
#include <stdio.h>
Program:
#include <stdlib.h>
int findP(int v) {
if (parent[v] != v)
parent[v] = findP(parent[v]);
return parent[v];
}
if (r1 != r2) {
if (rank[r1] > rank[r2])
parent[r2] = r1;
else if (rank[r1] < rank[r2])
parent[r1] = r2;
else {
parent[r2] = r1;
rank[r1]++;
}
}
}
recursive_quick_sort(edges, 0, E - 1);
if (x != y) {
result[e][0] = edge[0];
result[e][1] = edge[1];
result[e][2] = edge[2];
totalCost += edge[2];
e++;
unionSets(x, y);
}
}
int main() {
int V, E, edges[MAX][3];
printf("Enter number of vertices and edges: ");
scanf("%d %d", &V, &E);
kruskals(edges, V, E);
return 0;
}
Example 1
Output:
Dry Run:
Observations:
Kruskal’s Algorithm:
Union-Find Compression used: Makes sure that when we look for a node’s leader,
This way, future searches become much faster, reducing the time taken from slow,
Conclusion:
From Kruskal’s algorithm, I observed that sorting edges by weight and merging
components using the Union-Find technique allows us to construct the MST efficiently,