Kruskal's & Prim's
Algorithms
Discover two powerful greedy strategies for finding the minimum spanning tree of a weighted graph: one that sorts edges globally, and one that grows a tree from a single vertex.
What is a Spanning Tree?
A spanning tree of a connected graph \( G = (V, E) \) is a subgraph that includes every vertex in \( V \) and is a tree: connected with no cycles. It uses exactly \( |V| - 1 \) edges.
The Minimum Spanning Tree
Given a weighted, connected, undirected graph \( G = (V, E, w) \), a minimum spanning tree (MST) is a spanning tree \( T \) whose total edge weight is minimized:
Why Greedy Works for MSTs
Both Kruskal's and Prim's algorithms rely on the Cut Property, which guarantees that a greedy choice of the lightest edge crossing any cut is always safe.
This means at every step, picking the cheapest available edge that doesn't violate a constraint (no cycle for Kruskal's, crosses the frontier for Prim's) is provably optimal.
Kruskal's Algorithm
Kruskal's algorithm builds the MST by examining all edges globally, from lightest to heaviest, adding each edge if it does not create a cycle.
Prim's Algorithm
Prim's algorithm grows the MST one vertex at a time, always adding the cheapest edge that connects the growing tree to a vertex not yet in the tree.
Kruskal's vs Prim's: Key Difference
How to Apply Either Algorithm
Worked Example: The Graph
Consider this weighted graph with 5 vertices and 7 edges. We will find the MST using both algorithms.
Kruskal's Trace
Prim's Trace (start at A)
Same MST, Different Order
Both algorithms selected the same four edges: D-E(1), A-C(2), C-D(3), A-B(4) with total weight \(10\). But the order of selection differed.
| Step | Kruskal's | Prim's (from A) |
|---|---|---|
| 1 | D-E (1) | A-C (2) |
| 2 | A-C (2) | C-D (3) |
| 3 | C-D (3) | D-E (1) |
| 4 | A-B (4) | A-B (4) |
| Total | 10 | 10 |
Harder Example: 6-Vertex Graph
Solution: MST = Weight 22
Common Mistakes
Algorithm Comparison
| Property | Kruskal's | Prim's |
|---|---|---|
| Approach | Edge-centric (global sort) | Vertex-centric (grow tree) |
| Data Structure | Union-Find (Disjoint Set) | Priority Queue (Min-Heap) |
| Time Complexity | \( O(E \log E) \) | \( O(E \log V) \) |
| Best for | Sparse graphs (\( E \approx V \)) | Dense graphs (\( E \approx V^2 \)) |
| Starts with | Forest of singletons | Single source vertex |
| Result | Same MST | Same MST |
Question 1 of 5
A connected graph has 6 vertices. How many edges does its minimum spanning tree contain?
Question 2 of 5
In Kruskal's algorithm, when should you reject an edge?
Question 3 of 5
Which of the following is true about Prim's algorithm?
Question 4 of 5
The Cut Property guarantees that:
Question 5 of 5
A graph has edges with weights: 1, 2, 3, 4, 5, 6, 7 and 5 vertices. Kruskal's algorithm adds edges of weights 1, 2, 3, then considers weight 4. If weight 4 creates a cycle, it skips it and adds weight 5. What is the total MST weight?