Suppose five villages need to be connected using roads. Building every possible road will cost too much. We want to connect all villages using the lowest total road cost. But how do we select the roads without making unnecessary loops?
Many students find Kruskal's Algorithm difficult because they get confused while choosing edges and checking cycles. The main idea is actually simple: choose the cheapest useful connection first.
In this chapter, we will learn each idea from the beginning. You will understand the graph terms, see exactly why an edge is accepted or rejected, build the minimum spanning tree by hand, and then learn how the C program performs the same work.
Kruskal's Algorithm is a greedy algorithm used to find a Minimum Spanning Tree (MST) of a connected, weighted, undirected graph. It sorts all edges by weight and selects the smallest edge that does not form a cycle.
Why Do We Need Kruskal's Algorithm?

Imagine that five villages need a new cable network. Each possible connection has a different cost. If we build every possible connection, we spend money on cables that are not needed. If we build too few, some villages remain disconnected.
We need one connected network with the least possible total cost. This is the problem solved by a Minimum Spanning Tree. Kruskal's Algorithm gives us a systematic way to find it.
Basic Graph Terms You Must Know First
Before choosing any edge, understand these six words. They appear in almost every graph question.
What Is a Greedy Algorithm?
A greedy algorithm makes a good choice at the current step rather than trying all possible choices. Kruskal looks at the cheapest remaining edge and asks: "Can I add this without creating a cycle?" If the answer is yes, it selects that edge. If not, it skips it.
We call this a greedy choice. For Minimum Spanning Trees, this rule is safe when edges are processed from smallest weight to largest and cycles are avoided.
What Is a Minimum Spanning Tree (MST)?
A graph contains vertices (points) and edges (connections). In a weighted graph, each edge has a number such as distance, time or cost.
A spanning tree connects all vertices without creating any cycle. A minimum spanning tree is the spanning tree with the smallest possible total edge weight.
- Every vertex must be connected.
- No cycle is allowed.
- If there are V vertices, the spanning tree has exactly V − 1 edges.
- Among all valid spanning trees, the MST has the minimum total weight.
Difference Between a Graph, a Spanning Tree and an MST
A graph can have many extra edges and cycles. A spanning tree removes those extra connections but still reaches all vertices. There may be many different spanning trees; the one with the smallest total weight is the MST.
Understand a Cycle Visually
The triangle on the left has a loop. On the right, one edge is removed, so all points stay connected without a loop. An MST chooses the cheapest such tree.
Why Does a Tree Have V − 1 Edges?
Start with one vertex. No edge is needed yet. To bring a second vertex into the same connected group, we need one edge. To add a third new vertex, we need one more edge. Every extra vertex needs exactly one new connection.
That is why five vertices need 5 − 1 = 4 edges in a spanning tree. Adding a fifth edge between two vertices that are already connected would create a cycle.
Kruskal's Algorithm Example with Pictorial Representation
Consider this undirected graph with five vertices: A, B, C, D and E. Each number written near a line represents that edge's weight.
Original Weighted Graph
How Does Kruskal's Algorithm Work?
- Write down all edges with their weights.
- Sort the edges from the smallest weight to the largest.
- Select the smallest edge if it joins two groups that are not already connected.
- Skip the edge if adding it would make a cycle.
- Stop after V − 1 selected edges when the graph is connected.
Flow of the Algorithm
Important: In Kruskal, we do not have to start from A or any other particular vertex. The algorithm starts from the edge list. At first, each vertex is treated as a separate group. The groups grow as we select edges.
Step-by-Step Solution of the Example
First arrange every edge in ascending order of weight:
| Order | Edge | Weight |
|---|---|---|
| 1 | B–C | 1 |
| 2 | A–B | 2 |
| 3 | A–C | 3 |
| 4 | D–E | 4 |
| 5 | B–D | 5 |
| 6 | C–E | 7 |
| 7 | C–D | 8 |
Step 1: Choose B–C (Weight 1)
B and C are not connected yet. Add B–C. The total cost becomes 1.
Step 2: Choose A–B (Weight 2)
A is a new vertex. Add A–B. Now A, B and C belong to one connected group. Total cost = 1 + 2 = 3.
Step 3: Check A–C (Weight 3)
Do not add this edge. A can already reach C using A–B–C. Adding A–C would make a triangle (cycle). The total remains 3.
Step 4: Choose D–E (Weight 4)
D and E form another small connected group. Add D–E. Total cost = 3 + 4 = 7.
Step 5: Choose B–D (Weight 5)
This edge joins the group A–B–C with the group D–E. Add B–D. We now have four selected edges for five vertices, so the MST is complete.
Selected edges: B–C, A–B, D–E and B–D. The heavier edges C–E (7) and C–D (8) do not need to be checked after the tree is complete.
Complete Dry Run Table
This table shows every edge we examine until the MST is complete. Notice that an edge can be very cheap and still be rejected when it forms a cycle.
| Step | Edge | Weight | Decision | Total |
|---|---|---|---|---|
| 1 | B–C | 1 | Accept; connects B with C | 1 |
| 2 | A–B | 2 | Accept; adds A | 3 |
| 3 | A–C | 3 | Reject; makes A–B–C–A cycle | 3 |
| 4 | D–E | 4 | Accept; makes group D–E | 7 |
| 5 | B–D | 5 | Accept; joins both groups | 12 |
On a small phone, swipe the table sideways to see all columns.
How the Connected Groups Change
Instead of thinking about every line separately, watch how the groups of vertices join after each selected edge.
| After | Separate Connected Groups | Meaning |
|---|---|---|
| Start | {A} {B} {C} {D} {E} | All vertices are separate |
| B–C | {A} {B,C} {D} {E} | B and C join |
| A–B | {A,B,C} {D} {E} | A joins B and C |
| Skip A–C | {A,B,C} {D} {E} | No group changes |
| D–E | {A,B,C} {D,E} | D and E join |
| B–D | {A,B,C,D,E} | Everybody is connected |
Why stop here? We already have V − 1 = 4 accepted edges, and all five vertices belong to a single connected group. The remaining two heavier edges cannot reduce the total.
Final Minimum Spanning Tree
Interactive Kruskal's Algorithm Visualizer
Click Next Step to see which edge is selected or rejected. Watch the green edges build the MST and the red dashed edge show a cycle.
Try Kruskal's Algorithm Yourself
Step 0 of 5 · Total cost: 0
Start with an empty MST. Press Next Step to examine the smallest edge.
Selected edges: none
Understand Every Decision in the Interactive Diagram
The visualizer above follows the same five decisions shown in the dry run. Grey edges have not been processed. Green edges become part of the answer. A red dashed edge has been checked but rejected because it would make a cycle.
Kruskal's Algorithm Pseudocode
Pseudocode means writing the algorithm's logic in simple steps before writing a real program.
KRUSKAL(graph):
MST = empty
Sort all edges by increasing weight
Make a separate set for each vertex
For every edge (u, v, weight):
If FIND(u) is not equal to FIND(v):
Add edge (u, v) to MST
UNION(u, v)
If MST has V - 1 edges:
Stop
Return MST
Why Does Kruskal's Algorithm Use Union-Find?
Union-Find (also called Disjoint Set Union or DSU) helps us check whether two vertices are already connected.
Find the group or root to which vertex x belongs.
Join two different groups after selecting an edge.
After selecting B–C and A–B, the vertices A, B and C
are already in the same group.
So FIND(A) == FIND(C).
Adding A–C would make a cycle,
and the algorithm rejects that edge.
In the C program below, path compression makes future FIND operations quicker, while union by rank keeps the groups shallow.
Union-Find Step by Step
At the start, every vertex belongs to its own set. We can think of each set as a separate group of friends.
Make-Set: Create five individual groups: {A}, {B}, {C}, {D}, {E}.
Find: Before adding B–C, check the root of B and the root of C. They are different, so B–C is safe.
Union: Join the group of B with the group of C. Later, A–B joins A to this same group.
Cycle Check: When A–C comes, A and C already have the same root. So this edge is rejected.
Path Compression — Explained Simply
Suppose the parent links form A → B → C and C is the main root. Normally, finding A's root follows two links. With path compression, after finding C we directly set A's parent to C. The next lookup becomes faster.
int findSet(int x) {
if (parent[x] != x)
parent[x] = findSet(parent[x]);
return parent[x];
}
In this code, a vertex is the root when
parent[x] == x.
Otherwise, the function keeps searching.
On the way back, it updates parent links
to point directly to the root.
Union by Rank — Explained Simply
While joining two groups, we want to avoid creating a very long chain of parents. Union by rank attaches the shallower tree under the deeper tree. If both ranks are equal, we choose one root and increase its rank by one. This keeps future searches efficient.
In short: Find tells us whether an edge makes a cycle. Union updates the groups after a safe edge is chosen.
Kruskal's Algorithm C Program
This C program uses the same graph as our diagrams. It sorts the edges, rejects cycles using Union-Find and prints the selected edges with the total MST cost.
#include <stdio.h>
#include <stdlib.h>
#define V 5
#define E 7
typedef struct {
int u, v, weight;
} Edge;
int parent[V], rankValue[V];
void makeSet(void) {
for (int i = 0; i < V; i++) {
parent[i] = i;
rankValue[i] = 0;
}
}
int findSet(int x) {
if (parent[x] != x)
parent[x] = findSet(parent[x]);
return parent[x];
}
int unionSet(int a, int b) {
int rootA = findSet(a);
int rootB = findSet(b);
if (rootA == rootB)
return 0; /* Cycle would be formed */
if (rankValue[rootA] < rankValue[rootB]) {
parent[rootA] = rootB;
} else if (rankValue[rootA] > rankValue[rootB]) {
parent[rootB] = rootA;
} else {
parent[rootB] = rootA;
rankValue[rootA]++;
}
return 1;
}
int compareEdges(const void *a, const void *b) {
const Edge *x = (const Edge *)a;
const Edge *y = (const Edge *)b;
return (x->weight > y->weight) - (x->weight < y->weight);
}
int main(void) {
Edge edges[E] = {
{1, 2, 1}, /* B-C */
{0, 1, 2}, /* A-B */
{0, 2, 3}, /* A-C */
{3, 4, 4}, /* D-E */
{1, 3, 5}, /* B-D */
{2, 4, 7}, /* C-E */
{2, 3, 8} /* C-D */
};
const char names[] = "ABCDE";
int selected = 0, total = 0;
makeSet();
qsort(edges, E, sizeof(Edge), compareEdges);
printf("Kruskal's Algorithm\n");
for (int i = 0; i < E && selected < V - 1; i++) {
Edge e = edges[i];
if (unionSet(e.u, e.v)) {
printf("Add %c-%c (weight %d)\n",
names[e.u], names[e.v], e.weight);
total += e.weight;
selected++;
} else {
printf("Skip %c-%c (cycle)\n",
names[e.u], names[e.v]);
}
}
if (selected == V - 1)
printf("Minimum total cost = %d\n", total);
else
printf("Graph is disconnected: no single MST.\n");
return 0;
}
Output of the C Program
Kruskal's Algorithm
Add B-C (weight 1)
Add A-B (weight 2)
Skip A-C (cycle)
Add D-E (weight 4)
Add B-D (weight 5)
Minimum total cost = 12
How to run in VS Code:
Save the program as kruskal.c,
compile with
gcc -std=c11 -Wall -Wextra -pedantic kruskal.c -o kruskal,
and run .\kruskal.exe in Windows PowerShell.
C Program Explained in Simple Steps
Now connect the program with the hand-solved example. You do not need to memorise every line at once. Learn what each part is doing.
-
Edgestructure: Stores the two endpoints and their weight. For example,{1, 2, 1}represents B–C with weight 1 because A=0, B=1 and C=2. -
makeSet(): Creates one separate group for each vertex. Initially, every vertex is its own parent. -
compareEdges()andqsort(): Arrange the edges from lower weight to higher weight. -
findSet(): Finds the main representative, called the root, for a vertex's group. -
unionSet(): Returns 0 if both endpoints already belong to one group (cycle). Otherwise, it joins the groups and returns 1. -
Main loop:
Reads the sorted edges one by one.
It prints
Addwhen an edge is selected, orSkipwhen it creates a cycle. - Final result: The program stops after four accepted edges and prints total cost 12.
Trace the Important Program Variables
| Processed Edge | unionSet Result | selected | total |
|---|---|---|---|
| B–C (1) | 1 (accepted) | 1 | 1 |
| A–B (2) | 1 (accepted) | 2 | 3 |
| A–C (3) | 0 (cycle) | 2 | 3 |
| D–E (4) | 1 (accepted) | 3 | 7 |
| B–D (5) | 1 (accepted) | 4 | 12 |
edges array,
which makes the printed output easy to compare
with your handwritten solution.
Time and Space Complexity of Kruskal's Algorithm
| Operation | Complexity | Why? |
|---|---|---|
| Sort E edges | O(E log E) | Edges are arranged by weight. |
| Union-Find checks | O(E α(V)) | Optimised group checks are very fast. |
| Total time | O(E log E) | Sorting dominates the running time. |
| Extra DSU memory | O(V) | Parent and rank arrays. |
| Edges + DSU storage | O(E + V) | Includes the stored edge list. |
Here, V is the number of vertices, E is the number of edges, and α(V) represents a very slowly growing function used in Union-Find analysis. For semester exams, remember the overall time as O(E log E).
Our C program uses qsort();
the usual O(E log E) analysis assumes an efficient
comparison sort with that worst-case bound.
The C standard does not guarantee a particular
worst-case time complexity for qsort().
What Do These Complexity Symbols Mean?
Suppose a graph has 5 vertices and 7 edges. We write this as V = 5 and E = 7. Sorting all 7 edges takes the larger part of the work. Finding which group a vertex belongs to is usually very quick with the improved Union-Find structure.
O(E log E) does not mean the program runs for a fixed number of seconds. It tells us how the work grows when the number of edges grows. This is why it is called time complexity.
Why Is Kruskal's Algorithm Correct? (Easy Reason)
Imagine that the selected edges form two separate groups. To connect those groups, we must eventually choose an edge that goes from one group to the other. By checking edges in increasing order, Kruskal selects a cheapest safe connection when it joins the groups. Choosing a more expensive connection instead would not improve the total.
This idea is called the cut property of Minimum Spanning Trees. It explains why the greedy method works. You do not need the full mathematical proof for many introductory exams, but understanding this reason helps you remember the algorithm.
Special Cases Students Should Understand
1. What if two edges have equal weights?
Kruskal can consider either equal-weight edge first. Different choices may produce different MSTs, but their total minimum cost remains the same. That is why an MST is not always unique.
2. What if an edge has negative weight?
Negative weights are allowed in the mathematical MST problem. They are sorted before larger weights. We still add an edge only when it connects different groups.
3. What if the graph is disconnected?
A single spanning tree cannot connect all vertices because some components have no path between them. Kruskal can still find a minimum spanning forest: a minimum-cost tree inside each connected component.
4. What if the graph contains a self-loop?
A self-loop connects a vertex to itself, such as A–A. It can never help connect different vertices. Union-Find recognises that both ends are already in the same set, so it is skipped.
5. What if there are two edges between the same vertices?
The graph can have parallel edges. The algorithm still sorts all of them. After a smaller edge joins the vertices, another edge between those same connected groups would create a cycle and is rejected.
Kruskal's Algorithm vs Prim's Algorithm
| Feature | Kruskal's | Prim's |
|---|---|---|
| Basic idea | Choose globally cheapest safe edge. | Grow one tree from a chosen vertex. |
| Starting vertex | Not needed | Needed |
| Main helper | Sorted edges + Union-Find | Priority queue or array |
| Typical time | O(E log E) | O(E log V) with a suitable heap; O(V²) with an array |
| Disconnected graph | Produces a minimum spanning forest. | One run covers its starting component. |
Both algorithms solve the Minimum Spanning Tree problem. Kruskal's is often a convenient choice when the graph is provided as an edge list.
Applications of Kruskal's Algorithm
- Internet and cable networks: Connect offices or computers with low total cable cost.
- Road planning: Find a low-cost set of roads connecting several locations.
- Electricity distribution: Plan economical connections among power network points.
- Clustering: MSTs can help identify groups when selected expensive connections are removed.
Advantages and Limitations of Kruskal's Algorithm
- Easy to understand once edge sorting and cycles are clear.
- Works well when a graph is given as an edge list.
- Union-Find makes cycle checking efficient.
- Can build a minimum spanning forest for a disconnected graph.
- Edges must usually be sorted first.
- We need extra parent/rank arrays for Union-Find.
- It solves minimum network cost, not shortest path from a source.
- Wrong cycle checking can give a wrong answer.
Minimum Spanning Tree vs Shortest Path
This is a common exam confusion. A Minimum Spanning Tree tries to make the total weight of all chosen connections as small as possible. A shortest path algorithm, such as Dijkstra's Algorithm for non-negative weights, tries to make the cost of a route from one vertex to another as small as possible.
Example: A cable company wants to connect five buildings at the minimum overall installation cost. That is an MST problem. A traveller wants the shortest road route from building A to building E. That is a shortest path problem.
Common Mistakes Students Should Avoid
- Choosing an edge only because it is small: First check whether it creates a cycle.
- Forgetting to sort: Kruskal checks edges in non-decreasing weight order.
- Confusing a cycle with a path: A path is allowed. A cycle closes a loop.
- Using V instead of V − 1: A spanning tree on V vertices needs V − 1 edges.
- Assuming a disconnected graph has one MST: It has a minimum spanning forest instead.
Important Exam Questions
2 Marks: Define Kruskal's Algorithm.
Kruskal's Algorithm is a greedy algorithm that finds a minimum spanning tree by selecting edges in increasing order of weight while avoiding cycles.
5 Marks: Explain Kruskal's Algorithm with an Example.
Sort all edges by weight. Select the smallest edge that does not form a cycle and continue until V − 1 edges are chosen. In our example, we select B–C (1), A–B (2), D–E (4) and B–D (5). We skip A–C (3), as it creates a cycle. The minimum cost is 12.
Practice Questions with Answers
Try these small questions before your exam. They test the exact ideas used in this chapter.
-
For 8 vertices, how many edges must a spanning tree contain?
Answer: 8 − 1 = 7 edges.
-
Why was A–C (weight 3) rejected in our example?
Answer: A and C were already connected through A–B–C. Adding A–C would form a cycle.
-
Which data structure makes cycle checking efficient in Kruskal?
Answer: Disjoint Set Union (Union-Find).
-
For edges with weights 4, 1, 6 and 2, in what order will Kruskal check them?
Answer: 1, 2, 4, 6. Whether an edge is selected still depends on the cycle check.
-
Can two different MSTs have the same minimum cost?
Answer: Yes. Equal-weight edges may allow more than one valid MST.
10-Mark Answer Writing Format
If the question says "Explain Kruskal's Algorithm with an example and time complexity", write your answer in this sequence: definition → meaning of MST → steps → labelled graph → sorted edge list → accept/reject table → final MST and cost → complexity. If a C program is asked, add the Union-Find implementation and sample output.
Frequently Asked Questions
Is Kruskal's Algorithm a greedy algorithm?
Yes. It takes the lowest-weight safe edge at each step instead of trying every possible spanning tree.
Can Kruskal's Algorithm work with negative weights?
Yes. Negative edge weights are allowed for an undirected MST. We still sort all edges by weight and avoid cycles.
What happens if the graph is disconnected?
There is no single spanning tree that connects every vertex. Kruskal's Algorithm can produce a minimum spanning forest, which contains one minimum spanning tree for each connected component.
Quick Revision and Conclusion
Kruskal = Sort edges → Avoid cycles → Build MST.
It is a greedy graph algorithm that helps us connect all vertices at minimum total cost. In our example, the selected edges are B–C, A–B, D–E and B–D, with a total weight of 12.
For exams, practise drawing the graph, sorting edges, checking every cycle and explaining why the final tree contains V − 1 edges. The most important idea to remember is that the cheapest edge is selected only when it connects two different groups.
