Sort the graph edges with respect to their weights.
Start adding edges to the minimum spanning tree from the edge with the smallest weight until the edge of the largest weight. Only add edges which don’t form a cycle—edges which connect only disconnected components. Or as a simpler explanation, Step 1 – Remove all loops and parallel edges Step 2 – Arrange all the edges in ascending order of cost Step 3 – Add edges with least weight But how do you check whether two vertices are connected or not? That’s where the real-life example of Disjoint Sets come into use. Pseudocode Initialize integer variable MAX Create Int array id[MAX] Initialize node nodes and edges Function initialize() For loop i = 0 ; I <MAX; i++ i value stored to Id[i] End For loop Function root of integer x While(id[x] value Not Equal to x value) id[id[x]] is stored to id[x] id[x] = is stored to x End While loop return x Function union of int x and y Root of x is stored to p Root of y is stored to q Root of q is stored to p Function long long Kruskal with p[] argu Initialize x and y Initialize cost and minimumcost = 0 For with i=0; i less then edges;++i P[i].second.first is stored to x P[i].second.first is stored to y P[i].first is stored to cost If(root(x) not equal to root(y)) Minimumcost += cost; Call union with (x,y); End if End for loop Return minimumCost Main Initialize x and y Initialize weight, cost, minimumcost; Call initialize() Get the input nodes; Get the input nodes; For i=0; I less then edges;++i Get input x and y and weight Call make_pair function with ( weight, make_pair(x,y)) End For loop Call sort(p,p+edges); Call Kruskal(p) stroe value to minimumCost Print minimumCost value STOP