Prim's Algorithm grows a Minimum Spanning Tree (MST) from a single starting vertex, one edge at a time, always picking the cheapest edge that connects the existing tree to a vertex not yet in the tree. Kruskal's algorithm processes edges from cheapest to most expensive globally, while Prim's expands outward from a seed vertex.
Both produce the same MST (or one of equal cost if multiple MSTs exist), but they approach the problem differently. Prim's is vertex-centric. Kruskal's is edge-centric. This difference has real consequences for performance depending on whether the graph is dense or sparse.
Prim's Algorithm is a greedy algorithm for finding the Minimum Spanning Tree of a weighted, connected, undirected graph. It was developed by Vojtech Jarnik in 1930 and later rediscovered by Robert Prim in 1957.
The core idea:
At every step, the algorithm maintains two sets: vertices already in the MST, and vertices not yet in the MST. It always selects the minimum-weight edge that crosses from one set to the other. This is the greedy choice, and we will prove later why it is safe.
In this snapshot, vertices A and B are in the MST. The algorithm examines all edges crossing the boundary: A-C (3), A-D (7), B-C (2), B-E (5). It picks B-C with weight 2, the cheapest crossing edge. Vertex C joins the MST, and the process continues.
Consider this weighted undirected graph with 5 vertices:
Step 1: Start at vertex A. Mark A as visited. Add all edges from A to the priority queue.
Step 2: Extract the minimum edge (A-C, weight 1). C is not visited, so add C to the MST. Add all edges from C to unvisited vertices.
Step 3: Extract (C-B, weight 2). B is not visited, so add B. Add edges from B to unvisited vertices.
Step 4: Extract (C-E, weight 3). E is not visited, so add E. Add edges from E to unvisited vertices.
Step 5: Extract (A-B, weight 4). B is already visited. Skip it.
Extract (B-D, weight 5). D is not visited, so add D. All vertices are now in the MST.
The final MST looks like this:
The algorithm skipped the edge A-B (weight 4) because B was already in the MST by the time we processed it. The priority queue may contain stale entries, and we skip them if the target vertex is already visited.
Prim's and Dijkstra's shortest path algorithm share almost the same code structure. Both use a priority queue, both process one vertex at a time, and both greedily select the minimum from the queue.
The difference comes down to what value goes into the priority queue.
| Aspect | Dijkstra | Prim's |
|---|---|---|
| Purpose | Shortest path from source to all vertices | Minimum Spanning Tree |
| PQ stores | Total distance from source to vertex | Edge weight connecting vertex to MST |
| Key update | dist[v] = dist[u] + weight(u,v) | key[v] = weight(u,v) |
| Accumulates | Path distances | No, only individual edge weights |
| Works with negative weights? | No | Yes (only edge weights matter) |
In Dijkstra, when you relax an edge (u, v), you compute dist[u] + weight(u,v) and update if it is smaller than dist[v]. The distance accumulates as you travel further from the source.
In Prim's, when you examine an edge (u, v), you check whether weight(u,v) is smaller than the current key for v. There is no accumulation. Only the direct edge weight that connects v to the tree matters.
Here is the full implementation of Prim's Algorithm using an adjacency list and a min-heap. The min-heap lets us extract the cheapest crossing edge in O(log n) time at each step instead of scanning every candidate edge.
Implementation details worth highlighting:
inMST[u] when we dequeue and skip vertices already in the MST. This is simpler than maintaining a decrease-key operation on the heap.edgesAdded != n handles this case.Consider this larger graph with 7 vertices:
We start from vertex 0.
Iteration 1: Process vertex 0 (weight 0)
Iteration 2: Process vertex 1 (weight 2)
Iteration 3: Process vertex 2 (weight 3)
Iteration 4: Process vertex 4 (weight 1)
Iteration 5: Skip stale, then process vertex 3 (weight 5)
Iteration 6: Process vertex 5 (weight 6)
Iteration 7: Process vertex 6 (weight 4)
Final MST cost: 21
MST edges selected: 0-1 (2), 1-2 (3), 2-4 (1), 2-3 (5), 4-5 (6), 5-6 (4)
Why does always picking the cheapest crossing edge produce the MST? The answer lies in the Cut Property.
Cut Property: For any cut (partition of vertices into two non-empty sets) of a graph, if an edge is the unique minimum-weight edge crossing the cut, then that edge belongs to every MST. If it is one of several minimum-weight edges crossing the cut, it belongs to at least one MST.
At each step, Prim's algorithm creates a natural cut: vertices in the MST vs. vertices not in the MST. The cheapest edge crossing this cut is safe to add because of the Cut Property.
Here is the proof by contradiction:
Therefore, the greedy choice is always safe, and Prim's algorithm produces an MST.
Both algorithms solve the same problem (MST), but they take fundamentally different approaches. Choosing the right one depends on the graph structure.
| Aspect | Prim's | Kruskal's |
|---|---|---|
| Approach | Vertex-based, grows from a seed | Edge-based, picks globally cheapest edges |
| Data structure | Priority Queue (min-heap) | Union-Find (Disjoint Set Union) |
| Best for | Dense graphs (E close to V^2) | Sparse graphs (E close to V) |
| Complexity (binary heap) | O((V + E) log V) | O(E log E) |
| Complexity (optimal) | O(V^2) with adjacency matrix | O(E * alpha(V)) with path compression |
| Edge list needed? | No, works with adjacency list | Yes, needs all edges sorted |
| Starting vertex | Yes, starts from one vertex | No, processes edges globally |
| Multiple components | Finds MST of one component | Finds MST forest of all components |
| Easier to implement | Slightly more complex (PQ) | Simpler (sort + union-find) |
Either algorithm produces a valid MST. Prim's fits dense graphs, complete graphs, and adjacency-matrix input. Kruskal's fits sparse graphs, edge-list input, and disconnected graphs where you want an MST forest.
The time complexity depends on the implementation:
With Binary Heap (PriorityQueue): O((V + E) log V)
For connected graphs where E >= V - 1, this simplifies to O(E log V).
With Adjacency Matrix (no heap): O(V^2)
With Fibonacci Heap: O(E + V log V)
inMST array