Kruskal’s Algorithm is an algorithm that computes the weight of the minimum spanning tree of a connected undirected graph with edge weights in time and space.

Tip

This problem can also be solved by Prim’s Algorithm in

  • time and space, or
  • time and space.

Tip

This problem can also be solved by Boruvka’s Algorithm in time and space.

Algorithm

Lemma

Let denote the set of minimum spanning trees of , then

  1. Select an edge in .

  2. Solve for the graph obtained by contracting edge recursively.

Applying the lemma yields that the selected edges form a minimum spanning tree.

Applying an appropriate sorting algorithm (e.g., Merge Sort, Heapsort, Quicksort) to sort the edges and using a Disjoint Set Union to maintain the structure of the graph yield an algorithm that solves the problem in time and space.

int kruskal(int n, int m, const std::vector<int> &u, const std::vector<int> &v, const std::vector<int> &w) {
	std::vector<int> o(m);
	std::iota(o.begin(), o.end(), 0);
	std::ranges::sort(o, std::less(), [&](int i) -> int {
		return w[i];
	});
 
	DSU dsu(n);
	int sum = 0;
 
	for (int i : o) {
		if (dsu.merge(u[i], v[i])) {
			sum += w[i];
		}
	}
 
	return sum;
}