Program 9 (b)
Program 9 (b)
Algorithm:
1. Sort all edges in ascending order of their weights.
3. Iterate through the sorted edges and add an edge to the MST if it does not form a cycle
(using union-find to check).
4. Stop when the MST contains V−1V-1V−1 edges, where VVV is the number of vertices.
Source Code:
#include <stdio.h>
#include <stdlib.h>
struct Edge {
};
struct Graph {
int V, E;
};
struct Subset {
int parent;
int rank;
};
struct Graph* createGraph(int V, int E) {
graph->V = V;
graph->E = E;
return graph;
if (subsets[i].parent != i) {
return subsets[i].parent;
subsets[xroot].parent = yroot;
subsets[yroot].parent = xroot;
} else {
subsets[yroot].parent = xroot;
subsets[xroot].rank++;
}
int compareEdges(const void* a, const void* b) {
int V = graph->V;
int e = 0;
int i = 0;
subsets[v].parent = v;
subsets[v].rank = 0;
if (x != y) {
result[e++] = nextEdge;
unionSets(subsets, x, y);
}printf("Edge \tWeight\n");
}
free(subsets);
int main() {
int V, E;
scanf("%d", &V);
scanf("%d", &E);
kruskalMST(graph);
free(graph->edges);
free(graph);
return 0;
}
Sample Input and Output
Input:
Enter the number of vertices: 4
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
Output:
Running Kruskal's Algorithm to find MST...
Edge Weight
2-3 4
0-3 5
0 - 1 10