Kruskal's Algorithm
@kruskals_algorithmPseudo-code
function kruskal(graph):
# Step 1: Sort all edges by weight (smallest first)
sort edges E by weight
# Step 2: Initialize empty MST
MST = empty set
# Step 3: Create disjoint sets (each node is its own group)
make_set for each vertex in V
# Step 4: Process edges
for each edge e(u, v) in sorted edges:
# Check if adding edge forms a cycle
if find(u) != find(v):
# Safe to add edge
MST.add(e)
union(u, v)
return MST
- V The set of vertices (nodes) in the graph.
- E The set of edges, each with a weight (cost).
- e The current edge being checked from the sorted list.
- MST The resulting tree that connects all nodes with minimum total cost.
- infinity Represents a very large value, though not always directly needed in Kruskal.
Recipe Steps
List all connections — Imagine you have cities connected by roads with costs.
Sort by cheapest first — Arrange all roads from cheapest to most expensive.
Start building — Pick the cheapest road and add it.
Keep adding the next cheapest road, but skip it if it creates a loop.
Stop when all cities are connected. You now have the cheapest possible network.
Questions & Answers
- Uses Union-Find (Disjoint Set) for efficiency.
- Tip: Think of it as slowly building a network without creating loops.
- Common mistake: Forgetting cycle detection.
- Works best for sparse graphs (few edges).
Related Algorithms
Bellman-Ford Algorithm
The Bellman-Ford algorithm finds the shortest path from a source node to all other nodes, even when there are negative edge weights. It works by repeatedly improving distance estimates.
ViewDijkstra's Algorithm
Dijkstra's Algorithm finds the shortest path from one starting node to all other nodes in a graph by always expanding the currently closest node first.
ViewDinic's Algorithm
Dinic's Algorithm finds the maximum flow in a network by building layers using BFS and then sending flow using DFS in these layers, making it faster than simpler methods.
View