Suppose five towns must be connected by fibre-optic cable, and each possible link has a cost. You want every town reachable from every other, using the smallest total length of cable. The answer is a minimum spanning tree (MST): a subset of edges that connects all vertices, contains no cycles, and has the lowest possible total weight. Two classic greedy algorithms find it, Kruskal’s and Prim’s, and both are short enough to write from memory.
In this lesson you will learn
- What a spanning tree is and why it has V − 1 edges
- Kruskal’s algorithm with sorting and union-find
- Prim’s algorithm growing one tree from a start vertex
- Why these greedy choices are always correct
- Complexity and when to prefer each algorithm
This lesson uses Union-Find and qsort.
Kruskal’s Algorithm
#include <stdio.h>
#include <stdlib.h>
/* Kruskal: sort edges by weight, add each edge that does not form a cycle */
struct Edge { int u, v, w; };
int parent[16];
int find(int x) { return parent[x] == x ? x : (parent[x] = find(parent[x])); }
int by_weight(const void *a, const void *b) {
return ((const struct Edge *)a)->w - ((const struct Edge *)b)->w;
}
int main(void) {
const char *town[] = {"A", "B", "C", "D", "E"};
struct Edge e[] = {{0, 1, 4}, {0, 2, 3}, {1, 2, 1}, {1, 3, 2},
{2, 3, 4}, {3, 4, 2}, {2, 4, 6}};
int V = 5, E = 7, total = 0, used = 0;
qsort(e, E, sizeof e[0], by_weight);
for (int i = 0; i < V; i++) parent[i] = i;
for (int i = 0; i < E; i++) { /* could stop early once used == V - 1 */
int ru = find(e[i].u), rv = find(e[i].v);
if (ru == rv) {
printf("skip %s-%s (%d): would make a cycle\n", town[e[i].u], town[e[i].v], e[i].w);
continue;
}
parent[ru] = rv;
total += e[i].w;
used++;
printf("take %s-%s (%d)\n", town[e[i].u], town[e[i].v], e[i].w);
}
printf("Total cable length: %d\n", total);
return 0;
}
Output
take B-C (1)
take B-D (2)
take D-E (2)
take A-C (3)
skip A-B (4): would make a cycle
skip C-D (4): would make a cycle
skip C-E (6): would make a cycle
Total cable length: 8
- All edges are sorted by weight with
qsort, then examined from cheapest to most expensive. - An edge is taken only if its two ends are in different components; union-find answers that in almost O(1). Otherwise it would create a cycle and is skipped.
- A spanning tree of V vertices always has exactly V − 1 edges, so after 4 edges the tree is complete. The program keeps scanning only to show the skipped edges; a real implementation can stop early.
- The total cost is 8. Edges with equal weight may be processed in either order; the total stays the same.
Prim’s Algorithm
#include <stdio.h>
#include <limits.h>
#include <stdbool.h>
/* Prim: grow one tree, always adding the cheapest edge leaving it (O(V^2) version) */
#define V 5
int main(void) {
const char *town[V] = {"A", "B", "C", "D", "E"};
int g[V][V] = {
/* A B C D E */
{ 0, 4, 3, 0, 0 },
{ 4, 0, 1, 2, 0 },
{ 3, 1, 0, 4, 6 },
{ 0, 2, 4, 0, 2 },
{ 0, 0, 6, 2, 0 },
};
int key[V], from[V];
bool in_tree[V];
for (int i = 0; i < V; i++) { key[i] = INT_MAX; from[i] = -1; in_tree[i] = false; }
key[0] = 0; /* start from A */
int total = 0;
for (int step = 0; step < V; step++) {
int u = -1;
for (int v = 0; v < V; v++) /* cheapest vertex not yet in the tree */
if (!in_tree[v] && (u == -1 || key[v] < key[u])) u = v;
in_tree[u] = true;
if (from[u] != -1) {
printf("add %s-%s (%d)\n", town[from[u]], town[u], key[u]);
total += key[u];
}
for (int v = 0; v < V; v++) /* update neighbours */
if (g[u][v] && !in_tree[v] && g[u][v] < key[v]) { key[v] = g[u][v]; from[v] = u; }
}
printf("Total cable length: %d\n", total);
return 0;
}
Output
add A-C (3)
add C-B (1)
add B-D (2)
add D-E (2)
Total cable length: 8
- Prim’s starts from one vertex (A) and repeatedly adds the cheapest edge that connects the tree to a new vertex.
key[v]holds the cheapest known edge from the tree tov, andfrom[v]remembers which tree vertex that edge comes from.- After adding vertex
u, its neighbours’ keys are lowered ifuoffers a cheaper connection. This is very similar to Dijkstra’s algorithm, but the key is one edge’s weight, not a total distance. - Both algorithms find the same total cost, 8, here with the same edges added in a different order.
Kruskal vs Prim
| Kruskal | Prim | |
|---|---|---|
| Strategy | Cheapest edge anywhere that avoids a cycle | Cheapest edge leaving the current tree |
| Data structures | Sorted edge list + union-find | Key array, or a min-heap |
| Time | O(E log E) | O(V2) with arrays, O(E log V) with a heap |
| Best for | Sparse graphs, edge lists | Dense graphs, adjacency matrices |
Both are correct because of the cut property: for any split of the vertices into two groups, the cheapest edge crossing the split belongs to some minimum spanning tree. Each algorithm only ever adds such an edge.
Common Mistakes
- Confusing MST with shortest paths: an MST minimises the total edge weight, not the distance between two particular vertices.
- Running on a disconnected graph and expecting V − 1 edges; you get a spanning forest instead.
- Checking cycles with visited flags in Kruskal; two visited vertices can still be in different components. Use union-find.
- Using subtraction in the
qsortcomparator with very large weights, which can overflow.
Practice Exercises
Exercise 1. A triangle has edges A–B (2), B–C (3) and A–C (1). Which edges are in the MST, and what is its weight?
Show answer
A–C (1) and A–B (2), total 3. B–C (3) would close a cycle.
Exercise 2. How would you find a maximum spanning tree with Kruskal’s algorithm?
Show answer
Sort the edges in decreasing order of weight (or negate every weight) and run the same algorithm.
Frequently Asked Questions
Is the minimum spanning tree unique?
If all edge weights are different, yes. When some weights are equal there may be several MSTs, but they all have the same total weight.
Where are MSTs used in practice?
Designing road, power, water and computer networks, clustering data points by cutting the most expensive MST edges, and as a step in approximation algorithms for the travelling salesman problem.
Summary
- An MST connects all V vertices with V − 1 edges at minimum total weight.
- Kruskal sorts edges and uses union-find to avoid cycles.
- Prim grows one tree with the cheapest outgoing edge.
- Both are greedy and correct because of the cut property.
Next: Greedy Algorithms in C.
