Example 1 — Kruskal with union-find
The same graph as the Prim example.
#include <stdio.h>
#include <stdlib.h>
struct Edge { int u, v, w; };
static int parent[5];
static int find(int x) {
while (parent[x] != x) x = parent[x];
return x;
}
static int by_weight(const void *a, const void *b) {
return ((const struct Edge *)a)->w - ((const struct Edge *)b)->w;
}
int main(void) {
struct Edge e[] = {
{0, 3, 6}, {1, 2, 3}, {0, 1, 2}, {3, 4, 9},
{1, 4, 5}, {2, 4, 7}, {1, 3, 8}
};
int m = 7, total = 0;
for (int i = 0; i < 5; i++) parent[i] = i;
qsort(e, m, sizeof e[0], by_weight);
for (int i = 0; i < m; i++) {
int ru = find(e[i].u), rv = find(e[i].v);
if (ru != rv) {
parent[ru] = rv;
total += e[i].w;
printf("add %d - %d (%d)\n", e[i].u, e[i].v, e[i].w);
} else {
printf("skip %d - %d (%d)\n", e[i].u, e[i].v, e[i].w);
}
}
printf("total weight: %d\n", total);
return 0;
} How It Works
- After
qsort, edges are processed in weight order 2, 3, 5, 6, 7, 8, 9. - The first four edges join separate components, so they are added.
- The remaining edges would connect vertices that are already in the same component, so they are skipped. Total: 16, the same as Prim.
