In this article we show you the implementation of Kruskal’s Algorithm in C Programming Language. This algorithm is directly based on the generic MST (Minimum Spanning Tree) algorithm. A minimum spanning tree is a subgraph of the graph (a tree) with the minimum sum of edge weights.

Kruskal’s algorithm is a greedy algorithm in graph theory that finds a minimum spanning tree for a connected weighted graph. It finds a subset of the edges that forms a tree that includes every vertex, where the total weight of all the edges in the tree is minimized.

This algorithm initially appeared in “On the Shortest Spanning Subtree of a Graph and the Traveling Salesman Problem” research paper by Joseph B. Kruskal, Jr. in the proceedings of the American Mathematical Society Vol. 7, No. 1 (Feb., 1956), pp. 48-50.

Kruskal’s algorithm addresses two problems as mentioned below.

  • PROBLEM 1. Give a practical method for constructing a spanning subtree of minimum length.
  • PROBLEM 2. Give a practical method for constructing an unbranched spanning subtree of minimum length.

Kruskal’s algorithm is most suitable for sparse graphs (low number of edges).  This algorithm is practically used in many fields such as Traveling Salesman Problem, Creating Mazes and Computer Networks etc.

Pseudo code of the Kruskal’s Algorithm

Complexity of Kruskal’s Algorithm

The time complexity Of Kruskal’s Algorithm is: O(e log v).

Explanation:

Kruskal’s algorithm takes o(e log e) time in sorting of the edges. Here e is numbers of edges and v is the number of vertices in the graph. Further, it iterates all edges and runs a subroutine to find the cycles in the graph which is called union-find algorithm. The union-find algorithm requires o(log v) time and is applied after sorting of edges is completed.

So, Overall Kruskal’s algorithm requires o(e log v) time to run.

C Programming Implementation of Kruskal’s Algorithm

Here is the C program that implements this algorithm.

Output of the C Program