Kruskal’s algorithm

Kruskal’s algorithm finds a set of edges, which connected together create a tree with the minimal total weight – minimum spanning tree.

Read more on wikipedia.

Input

n m
v(1) v(2) w(1,2) (m times)
...
v(x) v(y) w(x,y)

n – number of vertices
m – number of edges
v(x) v(y) w(x,y) – edge between v(x) and v(y) with weight w(x,y)

Sample input

6 10
1 2 2
1 6 1
1 5 3
4 1 5
2 6 2
2 3 5
4 3 4
3 5 4
4 5 4
5 6 3

Output

The weight of a minimum spanning tree.

Complexity

First we need to sort edges in O(|E|log|E|) time, then unionSets and find operations can run in O(|V|) time in worst case, therefore whole algorithm runs in:

O(|E|log|E| + |E|·|V|) = O(|E| · (log|E| + |V|))

Source code