Minimum Spanning Trees: Fast Implementation of Prim's Algorithm
Minimum Spanning Trees: Fast Implementation of Prim's Algorithm
Spanning Trees
Fast Implementation
Algorithms: Design
and Analysis, Part II of Prim’s Algorithm
Running Time of Prim’s Algorithm
Tim Roughgarden
Prim’s Algorithm with Heaps
[Compare to fast implementation of Dijkstra’s algorithm]
Invariant #1: Elements in heap = vertices of V − X .
Invariant #2: For v ∈ V − X , key[v ] = cheapest edge (u, v ) with
i ∈ X (or +∞ if no such edges exist).
2 key[v]=2
X V −X
4
v
5
10 new key[w]=1
w
2
1
4
v
5
new X
key[v]=2
X V −X
X V −X
Pseudocode: When v added to X :
- For each edge (v , w ) ∈ E :
- If w ∈ V − X → The only whose key might have changed
(Update key if needed:)
- Delete w from heap
- Recompute key[w ]:=min{key[w ],cvw }
- Re-Insert into heap
Subtle point/exercise:
Think through book-keeping needed to pull this off
Tim Roughgarden
Running Time with Heaps
- Dominated by time required for heap operations
- (n − 1) Inserts during preprocessing
- (n − 1) Extract-Mins (one per iteration of while loop)
- Each edge (v , w ) triggers one Delete/Insert combo
[When its first endpoint is sucked into X ]
⇒ O(m) heap operations [Recall m ≥ n − 1 since G connected]
⇒ O(m log n) time [As fast as sorting!]
Tim Roughgarden