
About the author
Mallikarjuna Mallisetty
General programming
Mallikarjuna shares practical programming tutorials and foundational concepts designed to help developers learn by building and experimenting.
View LinkedIn profile ↗#include <stdio.h>
#include <stdlib.h>
#define MAX 100
struct Edge {
int src, dest, weight;
};
int parent[MAX];
int find(int i) {
if (parent[i] != i)
parent[i] = find(parent[i]);
return parent[i];
}
void unionSets(int u, int v) {
int setU = find(u);
int setV = find(v);
parent[setU] = setV;
}
int compare(const void *a, const void *b) {
return ((struct Edge *)a)->weight - ((struct Edge *)b)->weight;
}
int main() {
int V = 4, E = 5;
struct Edge edges[] = {
{0, 1, 10}, {0, 2, 6}, {0, 3, 5}, {1, 3, 15}, {2, 3, 4}
};
for (int i = 0; i < V; i++) parent[i] = i;
qsort(edges, E, sizeof(edges[0]), compare);
int totalWeight = 0;
printf("Edges in MST:\n");
for (int i = 0, count = 0; count < V - 1 && i < E; i++) {
if (find(edges[i].src) != find(edges[i].dest)) {
printf("%d - %d\n", edges[i].src, edges[i].dest);
totalWeight += edges[i].weight;
unionSets(edges[i].src, edges[i].dest);
count++;
}
}
printf("Total weight: %d\n", totalWeight);
return 0;
}