Sub topic 11
Running Time and Choosing Between Prim and Kruskal
This chapter assumes you know Big-O notation, the DisjointSet and kruskal code from the Kruskal chapter, and the heap-based prim code from the Prim chapter. Throughout, V is the number of vertices and E is the number of edges.
Where the time goes in Kruskal
Kruskal's algorithm does two kinds of work:
- It sorts all E edges by weight, which costs O(E log E).
- It makes up to 2E
findcalls and V − 1 successfulunioncalls. With union by rank and path compression, each call costs O(α(V)) amortized. α is the inverse Ackermann function, and it stays below 5 for any input you could store.
Sorting dominates, so the total is O(E log E). A simple graph has at most V² edges, so log E ≤ 2 log V, and O(E log E) is the same bound as O(E log V).
If the edges arrive already sorted, or the weights are small integers that radix sort can handle, the sorting cost disappears. Kruskal then runs in nearly linear time, O(E α(V)).
Where the time goes in Prim
The lazy Prim from the previous chapter pushes one heap entry per edge it examines, so the heap can grow to O(E) entries. Each push and pop costs O(log E). The total is O(E log E) = O(E log V), the same bound as Kruskal.
You can change the priority queue to change the bound:
| Priority queue | Prim running time | Best fit |
|---|---|---|
| Binary heap (lazy or with decrease-key) | O(E log V) | Sparse graphs |
| Fibonacci heap | O(E + V log V) | Theoretical interest; large constants in practice |
| Unsorted array | O(V²) | Dense graphs, where E is close to V² |
The array version is worth knowing. When E is around V², a heap costs O(V² log V), while a plain scan of an array costs O(V²).
Prim for dense graphs
This version stores the graph as an adjacency matrix. It keeps best[u], the lightest known edge from the tree to u, and on each step it scans for the cheapest vertex not yet in the tree. There is no heap.
INF = float("inf")
def prim_dense(w):
# w: n x n matrix; w[u][v] is the edge weight, INF if there is no edge
n = len(w)
in_tree = [False] * n
best = [INF] * n
parent = [-1] * n
best[0] = 0
total = 0
mst = []
for _ in range(n):
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] == INF:
break # remaining vertices are unreachable
in_tree[v] = True
total += best[v]
if parent[v] != -1:
mst.append((parent[v], v, best[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
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)])The outer loop runs V times, and each pass does two O(V) scans, so the total is O(V²) no matter how many edges the graph has.
Choosing between them
These practical points also matter:
- Input format. Kruskal works directly on an edge list. Prim needs an adjacency list or an adjacency matrix.
- Memory. Kruskal keeps and sorts every edge. Heap-based Prim needs the adjacency list plus a heap that can grow to O(E) entries.
- Early stopping. Kruskal can stop once it has accepted V − 1 edges. Prim can stop once every vertex is in the tree.
- Disconnected graphs. Kruskal produces a minimum spanning forest without any changes. Prim spans only the start vertex's component unless you restart it from each unvisited vertex.
Exercise
A graph has V = 10,000 vertices and about 50 million edges, and it is stored as an adjacency matrix. Which algorithm should you use, and roughly how many basic operations does each option need?
Show answer
Use array-based Prim. It needs about V² = 10^8 operations. Kruskal and heap-based Prim each need about E log V ≈ 5×10^7 × 13 ≈ 6.5×10^8 operations, and Kruskal must also first extract all 50 million edges from the matrix into a list.
Exercise
The edges arrive as a list already sorted by weight. What is Kruskal's running time in this case?
Show answer
O(E α(V)), which is nearly linear. Sorting is skipped, so the only cost left is the union-find operations.