Krushkals
Krushkals
h>
#include <stdlib.h>
#define MAX 100
struct Edge {
int src, dest, weight;
};
struct Graph {
int V, E;
struct Edge edges[MAX];
};
struct Subset {
int parent;
int rank;
};
int find(struct Subset subsets[], int i) {
if (subsets[i].parent != i) {
subsets[i].parent = find(subsets, subsets[i].parent);
}
return subsets[i].parent;
}
void unionSet(struct Subset subsets[], int x, int y) {
int xroot = find(subsets, x);
int yroot = find(subsets, y);
if (subsets[xroot].rank < subsets[yroot].rank) {
subsets[xroot].parent = yroot;
} else if (subsets[xroot].rank > subsets[yroot].rank) {
subsets[yroot].parent = xroot;
} else {
subsets[yroot].parent = xroot;
subsets[xroot].rank++;
}
}
int compareEdges(const void* a, const void* b) {
struct Edge* edgeA = (struct Edge*)a;
struct Edge* edgeB = (struct Edge*)b;
return edgeA->weight - edgeB->weight;
}
void kruskalMST(struct Graph* graph) {
int V = graph->V;
struct Edge result[MAX];
int e = 0;
int i = 0;
qsort(graph->edges, graph->E, sizeof(graph->edges[0]),
compareEdges);
struct Subset* subsets = (struct Subset*)malloc(V * sizeof(struct
Subset));
for (int v = 0; v < V; ++v) {
subsets[v].parent = v;
subsets[v].rank = 0;
}
while (e < V - 1 && i < graph->E) {
struct Edge nextEdge = graph->edges[i++];
int x = find(subsets, nextEdge.src);
int y = find(subsets, nextEdge.dest);
if (x != y) {
result[e++] = nextEdge;
unionSet(subsets, x, y);
}
}
printf("Following are the edges in the constructed MST:\n");
for (i = 0; i < e; ++i) {
printf("%d -- %d == %d\n", result[i].src, result[i].dest,
result[i].weight);
}
free(subsets);
}
int main() {
int V, E, i;
struct Graph* graph = (struct Graph*)malloc(sizeof(struct Graph));
printf("Enter the number of vertices: ");
scanf("%d", &V);
printf("Enter the number of edges: ");
scanf("%d", &E);
graph->V = V;
graph->E = E;
printf("Enter the edges (source, destination, weight):\n");
for (i = 0; i < E; i++) {
printf("Edge %d: ", i + 1);
scanf("%d %d %d", &graph->edges[i].src, &graph-
>edges[i].dest, &graph->edges[i].weight);
}
kruskalMST(graph);
free(graph);
return 0;
}