Kruskal's MST visualization

Sort edges by weight and add each one unless it would create a cycle (union–find).

Consider edges from lightest to heaviest. An edge joining two different components is safe to add; one inside a component would close a cycle.

A disjoint-set (union–find) structure answers "same component?" in near-constant time. On a disconnected graph Kruskal naturally produces a minimum spanning forest.

Complexity

Time: best O(E log E), average O(E log E), worst O(E log E). Space: O(V). Difficulty: Intermediate.

Pseudocode

procedure kruskal(G):
  sort edges by weight
  make every vertex its own set
  for each edge (u, v, w) in order:
    if find(u) ≠ find(v):
      union(u, v); add edge to MST
    else: skip — would form a cycle
  return MST (a forest if G is disconnected)

More graphs algorithms