Sub topic 11
Running Time and Choosing Between Prim and Kruskal
This chapter assumes you have read the chapters on Kruskal's algorithm and Prim's algorithm. It also assumes you can read Big-O notation and know how a binary heap supports push and pop in O(log n) time. Throughout, V is the number of vertices and E is the number of edges.
Kruskal's and Prim's algorithms both produce a minimum spanning tree, and on paper their textbook bounds look identical. In practice the better choice depends on graph density, on how the graph is stored, and on which priority queue you use. This chapter works out where each running time comes from, shows a third variant of Prim that wins on dense graphs, and ends with decision criteria.
Where Kruskal's Time Goes
Kruskal's algorithm does two things:
- It sorts all E edges by weight.
- It scans the sorted list and calls
unionon the disjoint-set structure once per edge, or fewer times if it stops early after V − 1 edges.
Sorting costs O(E log E). With union by rank and path compression (or path halving), each disjoint-set operation runs in amortized O(α(V)) time. Here α is the inverse Ackermann function, which is at most 4 for any input that fits in physical memory. The scan therefore costs O(E α(V)), which is effectively linear.
Sorting dominates, so Kruskal runs in O(E log E).
Why O(E log E) equals O(E log V)
A simple undirected graph has at most V(V − 1)/2 edges, so E < V². Taking logarithms gives log E < 2 log V. Constant factors disappear inside Big-O, so O(E log E) = O(E log V). The two forms are interchangeable, and textbooks use both.
If the graph has parallel edges (a multigraph), E is not bounded by V². In that case, keep only the lightest edge between each pair of vertices before running either algorithm. The heavier parallel edges can never be in an MST, and removing them restores the bound.
When sorting is cheaper
The O(E log E) term comes from comparison sorting. You can avoid it in two cases:
- Pre-sorted input. If the edges already arrive in weight order, Kruskal runs in O(E α(V)).
- Small integer weights. If weights are integers in a range of size W, counting sort or radix sort orders the edges in O(E + W). Kruskal is then close to linear.
Where Prim's Time Goes
Prim's running time depends on the priority queue. The chapter on Prim's algorithm used the lazy version, which pushes a new heap entry every time it sees an edge to an unvisited vertex and discards stale entries when it pops them.
Lazy Prim with a binary heap
- Each edge is examined from both endpoints, and each examination can push one entry. That gives at most 2E pushes.
- Each push and pop costs O(log(heap size)). The heap can hold O(E) entries, so each costs O(log E).
The total is O(E log E), which again equals O(E log V). The memory cost is O(E) for the heap, since stale entries stay in it until they are popped.
Eager Prim with decrease-key
The eager version keeps at most one heap entry per vertex: the cheapest known edge connecting that vertex to the tree. When a cheaper edge appears, the algorithm lowers that vertex's key with a decrease-key operation instead of pushing a duplicate.
- V pops, each O(log V).
- Up to E decrease-key operations, each O(log V) on a binary heap.
The total is O((V + E) log V) = O(E log V) for a connected graph, with only O(V) heap memory. Python's heapq has no decrease-key, so eager Prim in Python needs an indexed heap that you write yourself. That is why the lazy version is the usual choice in Python.
Prim with a Fibonacci heap
A Fibonacci heap supports decrease-key in amortized O(1) time and delete-min in amortized O(log V). Prim then runs in O(E + V log V), which is asymptotically better than either binary-heap version when E is much larger than V. The constant factors are large and the structure is complicated, so Fibonacci heaps rarely beat a binary heap in practice.
Prim with a plain array: O(V²)
For dense graphs you can drop the heap. Keep an array best[v] holding the cheapest known edge weight from the tree to each vertex. At each of V steps, scan the array for the minimum (O(V)), add that vertex, and update its neighbors (O(V) with an adjacency matrix). The total is O(V²), with no logarithm.
When E is close to V², O(V²) is the same as O(E). That is linear in the input size, and nothing can do better because every edge must be read at least once.
import math
def prim_dense(w):
# w: n x n matrix; w[u][v] is the edge weight, or math.inf if there is no edge
n = len(w)
in_tree = [False] * n
best = [math.inf] * n # cheapest known edge from the tree to each vertex
parent = [-1] * n
best[0] = 0
total = 0
mst = []
for _ in range(n):
# Linear scan for the closest vertex not yet in the tree.
v = -1
for u in range(n):
if not in_tree[u] and (v == -1 or best[u] < best[v]):
v = u
if best[v] == math.inf:
break # the remaining vertices are unreachable from vertex 0
in_tree[v] = True
total += best[v]
if parent[v] != -1:
mst.append((parent[v], v, best[v]))
# Relax every edge out of v.
for u in range(n):
if not in_tree[u] and w[v][u] < best[u]:
best[u] = w[v][u]
parent[u] = v
return total, mst
INF = math.inf
w = [
[INF, 1, 4, INF],
[1, INF, 3, 2 ],
[4, 3, INF, 5 ],
[INF, 2, 5, INF],
]
print(prim_dense(w)) # (6, [(0, 1, 1), (1, 3, 2), (1, 2, 3)])This is the same four-vertex graph used in earlier chapters, and it produces the same tree with total weight 6.
The Full Comparison
| Algorithm and data structure | Time | Extra memory | Best suited to |
|---|---|---|---|
| Kruskal, comparison sort + union-find | O(E log V) | O(V) plus the sorted edge list | Sparse graphs, edge-list input |
| Kruskal, pre-sorted or radix-sorted edges | O(E α(V)) | O(V) | Integer weights, streamed sorted edges |
| Prim, lazy binary heap | O(E log V) | O(E) heap | Sparse graphs, adjacency lists, Python |
| Prim, eager indexed binary heap | O(E log V) | O(V) heap | Sparse graphs where heap memory matters |
| Prim, Fibonacci heap | O(E + V log V) | O(V) | Mainly of theoretical interest |
| Prim, array scan | O(V²) | O(V) | Dense graphs, adjacency matrices |
Sparse Versus Dense: Working the Numbers
A graph is sparse when E grows roughly like V, for example road networks where each intersection has a handful of roads. A graph is dense when E grows roughly like V², for example complete graphs of pairwise distances between points.
Compare O(E log V) with O(V²) on two inputs. Use log₂ and treat the counts as rough operation estimates, not timings.
| Graph | V | E | E log₂ V | V² |
|---|---|---|---|---|
| Sparse (road-like) | 1,000,000 | 3,000,000 | about 6 × 10⁷ | 10¹² |
| Dense (complete) | 2,000 | about 2,000,000 | about 2.2 × 10⁷ | 4 × 10⁶ |
On the sparse graph, the array version is more than ten thousand times slower. On the dense graph it is about five times faster, and its simple loops have small constant factors.
The crossover sits roughly where E log V ≈ V², that is, E ≈ V² / log V. Above that density, use array-based Prim. Below it, use Kruskal or heap-based Prim.
Practical Factors Beyond Big-O
Input format
Kruskal consumes an edge list directly. Prim needs adjacency lists, or a matrix for the array version. Converting between formats costs O(V + E) time and extra memory. If your data already arrives in one format, that often settles the choice for sparse graphs.
Constant factors in Python
In Python, sorted() runs in C, while every heapq.heappush call returns to the interpreter between operations. Kruskal makes one C-level sort followed by a tight loop of find calls. Lazy Prim makes up to 2E separate heap calls. On sparse graphs in Python, Kruskal is often faster even though both have the same bound. In C++ or Java the gap shrinks, and Prim's better memory locality on adjacency lists can win.
Early termination
Kruskal can stop after accepting V − 1 edges, but it has to sort every edge first. If the MST uses only light edges, most of the sort is wasted. Building a heap of all edges in O(E) and popping until V − 1 edges are accepted avoids this. Prim has no comparable shortcut, because it has to reach every vertex.
Disconnected graphs
Kruskal handles a disconnected graph without changes and returns a minimum spanning forest. Prim covers only the start vertex's component, and the array version above stops when best[v] is infinite. The chapter on minimum spanning forests covers how to restart Prim.
Common Errors
- Using an adjacency matrix with heap-based Prim. Scanning a matrix row costs O(V) per vertex no matter how many edges exist, so the total is at least O(V²). You pay for the heap's logarithm and get none of its benefit on sparse graphs.
- Using the array version on a sparse graph. It always costs O(V²), even when E ≈ V.
- Forgetting that the lazy heap holds O(E) entries. On a dense graph with millions of edges, the heap can use far more memory than the O(V) you might expect.
- Leaving parallel edges in the input. A multigraph with many duplicate edges inflates E and breaks the bound log E ≤ 2 log V. Keep only the lightest edge between each pair of vertices.
Exercise
A graph has V = 5,000 vertices and every pair of vertices is connected, so E ≈ 12.5 million. Estimate the operation counts for heap-based Prim, O(E log₂ V), and array-based Prim, O(V²). Which should you use?
Show answer
log₂ 5000 ≈ 12.3, so E log₂ V ≈ 12.5 × 10⁶ × 12.3 ≈ 1.5 × 10⁸. V² = 2.5 × 10⁷. The array version does about six times fewer operations and needs no heap, so use array-based Prim.
Exercise
Explain why O(E log E) and O(E log V) describe the same running time for a simple graph, and name one kind of input where this argument fails unless you preprocess it.
Show answer
A simple graph has E ≤ V(V − 1)/2 < V², so log E < 2 log V, and the factor of 2 vanishes inside Big-O. The argument fails for multigraphs with many parallel edges, because E is then unbounded relative to V. Keeping only the lightest edge between each pair of vertices restores E < V².
Exercise
Your edges have integer weights from 1 to 100 and arrive as an edge list with V = 10⁶ and E = 4 × 10⁶. Which algorithm and sorting method give the best bound, and what is that bound?
Show answer
Use Kruskal and sort the edges with counting sort over the 100 possible weights in O(E + 100) time. The union-find scan costs O(E α(V)), so the total is O(E α(V)), which is effectively linear and beats the O(E log V) bound of comparison-sort Kruskal or heap-based Prim.
Exercise
In prim_dense, what happens if vertex 3 has no edges at all (its row and column are all math.inf), and why does the loop not crash?
Show answer
After vertices 0, 1, and 2 join the tree, the scan selects vertex 3 because it is the only vertex left, but best[3] is still math.inf. The check if best[v] == math.inf: break exits the loop before vertex 3 is added. The function then returns the spanning tree of vertex 0's component only.