An algorithm which is used to create a minimum spanning tree is attributed to Kruskal’s algorithm. The nodes of the graph are initially considered as n distinct partial trees with one node each. At each step of the algorithm, two distinct partial trees are connected into a single partial tree by an edge of the graph. When only one partial tree exists (after n-1 such steps), it is a minimum spanning tree.

The concern is what connecting arc to use at each step. The answer is to use the arc of minimum cost that connects two distinct trees. To do this, the arcs can be placed in a priority queue based on the weight. The arc of lowest weight is then examined to see if it connects two distinct trees.

To determine if an arc (x, y) connects distinct trees, we can implement the trees with a father field in each node. Then we can traverse all ancestors of x and y to obtain the roots of the trees containing them. If the roots of the two trees are the same node, x and y nodes are already in the same tree, arc (x, y) is discarded, the arc of next lowest weight is examined. Combining two trees simply involves setting the father of the root of one to the root of the other.

Algorithm

  • Forming the initial priority queue, i.e., O(e log e)
  • Removing the minimum weight arc and adjusting the priority queue, i.e., O(log e).
  • Locating the root of a tree, i.e., O(log n).
  • Initial formation of n trees, i.e., O(n).
  • Assume n < e.

C++ implementation of Kruskal’s Algorithm

Output: