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
- Breadth-First Search — Explore level by level with a queue — gives shortest paths in unweighted graphs.
- Depth-First Search — Go as deep as possible along each branch before backtracking.
- Dijkstra's Shortest Path — Greedily settle the closest unsettled vertex using a priority queue.
- Bellman–Ford — Relax every edge V−1 times; handles negative weights and detects negative cycles.
- Prim's MST — Grow one tree by always adding the cheapest edge leaving it.
- Topological Sort (Kahn) — Order a DAG so every edge points forward, by repeatedly removing zero in-degree vertices.
- Floyd–Warshall — All-pairs shortest paths by allowing one more intermediate vertex k at a time.
- A* Pathfinding — Best-first search on a grid using cost-so-far g plus a heuristic h towards the goal.