Kruskal’s Algorithm in Data Structure with Example

Chapter 56
Data Structure • Graph Algorithms

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.

Quick Answer: What is Kruskal's Algorithm?

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?

Kruskal’s Algorithm in Data Structure with Example

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.

Remember: Kruskal's Algorithm finds the minimum total network cost. It does not find the shortest route from one particular village to another. That is a different type of problem.

Basic Graph Terms You Must Know First

Before choosing any edge, understand these six words. They appear in almost every graph question.

Vertex (Node) A point in a graph. For example, A represents one village.
Edge A line connecting two vertices. A–B means there is a connection between A and B.
Weight The number written on an edge. It might represent money, distance or length.
Undirected Graph A connection can be used in both directions, such as A to B and B to A.
Connected Graph Every vertex can be reached from every other vertex by following edges.
Cycle A closed route that brings you back to the starting vertex, such as A → B → C → A.

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

Cycle and tree diagram On the left all three edges form a triangle. On the right only two edges remain, so there is no cycle. Cycle (extra edge) No cycle (tree) A B C A B C

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

Original weighted graph A-B weight 2, A-C 3, B-C 1, D-E 4, B-D 5, C-E 7 and C-D 8. 2 3 1 4 5 7 8 A B C D E
Figure 1: A weighted undirected graph containing 5 vertices and 7 edges.
5Vertices (V)
7Edges (E)
4Required MST edges

How Does Kruskal's Algorithm Work?

  1. Write down all edges with their weights.
  2. Sort the edges from the smallest weight to the largest.
  3. Select the smallest edge if it joins two groups that are not already connected.
  4. Skip the edge if adding it would make a cycle.
  5. Stop after V − 1 selected edges when the graph is connected.
Easy Memory Trick: Sort → Check Cycle → Add or Skip → Repeat.

Flow of the Algorithm

1. Sort Edges 2. Take Cheapest 3. Check Cycle 4. Add or Skip 5. Stop at V − 1

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:

OrderEdgeWeight
1B–C1
2A–B2
3A–C3
4D–E4
5B–D5
6C–E7
7C–D8

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.

Minimum Spanning Tree Cost = 1 + 2 + 4 + 5 = 12

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.

StepEdgeWeightDecisionTotal
1B–C1Accept; connects B with C1
2A–B2Accept; adds A3
3A–C3Reject; makes A–B–C–A cycle3
4D–E4Accept; makes group D–E7
5B–D5Accept; joins both groups12

On a small phone, swipe the table sideways to see all columns.

MST Cost = 1 + 2 + 4 + 5 = 12

How the Connected Groups Change

Instead of thinking about every line separately, watch how the groups of vertices join after each selected edge.

AfterSeparate Connected GroupsMeaning
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

Final minimum spanning tree Selected edges B-C weight 1, A-B 2, D-E 4 and B-D 5. Total minimum cost is 12. 1 2 4 5 A B C D E
Figure 2: The green edges connect all vertices with no cycle and the lowest total cost, 12.

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

Not processed Selected Rejected (cycle)
Interactive Kruskal graph Use Next Step and Previous to highlight selected and rejected edges. 2 3 1 4 5 7 8 A B C D E

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.

Try this: After Step 2, pause and imagine adding A–C. You can go A → B → C even without A–C. Adding it would close the loop. That one observation is the easiest way to understand Kruskal's cycle check.

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(x)

Find the group or root to which vertex x belongs.

UNION(x, y)

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.

  1. Edge structure: 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.
  2. makeSet(): Creates one separate group for each vertex. Initially, every vertex is its own parent.
  3. compareEdges() and qsort(): Arrange the edges from lower weight to higher weight.
  4. findSet(): Finds the main representative, called the root, for a vertex's group.
  5. unionSet(): Returns 0 if both endpoints already belong to one group (cycle). Otherwise, it joins the groups and returns 1.
  6. Main loop: Reads the sorted edges one by one. It prints Add when an edge is selected, or Skip when it creates a cycle.
  7. 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)11
A–B (2)1 (accepted)23
A–C (3)0 (cycle)23
D–E (4)1 (accepted)37
B–D (5)1 (accepted)412
Code note: This beginner program uses the five-vertex example already shown in this chapter, rather than asking for input. The graph is fixed inside the 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 edgesO(E log E)Edges are arranged by weight.
Union-Find checksO(E α(V))Optimised group checks are very fast.
Total timeO(E log E)Sorting dominates the running time.
Extra DSU memoryO(V)Parent and rank arrays.
Edges + DSU storageO(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

Advantages
  • 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.
Limitations
  • 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.

  1. For 8 vertices, how many edges must a spanning tree contain?

    Answer: 8 − 1 = 7 edges.

  2. 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.

  3. Which data structure makes cycle checking efficient in Kruskal?

    Answer: Disjoint Set Union (Union-Find).

  4. 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.

  5. 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.

Tags

Post a Comment

0 Comments
* Please Don't Spam Here. All the Comments are Reviewed by Admin.
Join Telegram Exam updates and free resources