(rev. 03/07/2010)
Priority Queue Version of Prim's Algorithm
G is a connected graph with n nodes and m edges.
For data structures for this algorithm, we use a set-up similar to the one for
the priority queue version of Dijkstra's algorithm. (See the image called
"DsAlg_Heap.jpg")
- The graph is represented as an array of edge lists, indexed by node
number. Indexes run from 1 to n, where n is the number of nodes in the
graph.
- There is a parallel array called "nearest" -- nearest[j]=k where cost
(k,j) is minimal over all k ∈ S. nearest is initialized to "all 1".
- The set S is represented by an array of Boolean flags. S[j]==true means
j ∈ S. S is initialized to "all false" except S[1] == true.
- Create an empty set of edges, MST.
- Create an empty priority queue PQ for pairs (j, c) where j is the name of
a node and c is cost(nearest[j], j). The sense of priority is that LOW c
is HIGH priority.
/* Note: Initializations in steps 2-5 do Θ(n) work.*/
- FOR j = 2 to n,
- IF edge (1, j) exists in G THEN insert (j, cost(1,j))
into PQ.
- ELSE insert (j, ∞) into PQ
/* Note: Initializations in step 6 do Θ(nlog(n)) work.*/
- WHILE PQ is not empty DO
- Remove one (k, c) from PQ
- insert k into S
- Insert (nearest[k], k) into MST
- FOR each edge of the form (k, j) such that j ∉ S
DO
- IF cost (k, j) < current priority of j THEN
- nearest[j] = k
- perform change key on the (j, c) in PQ, so that now
c=cost(k,j)
/* Note: The outer WHILE loop iterates n-1 times. Each removal of a
(k, c) does O(log(n)) work. In the worst case Θ(nlog(n)) work is
required for all n-1 removals.
Inserting k into S and (nearest[k], k) into MST is O(1).
Over the entire run of the WHILE loop, each edge of G is processed
at most twice, and this processing will result in a key change at most
once. Therefore the total amount of work attributable to that part of the
algorithm in the worst case is Θ(mlog(n))
Therefore the algorithm above is Θ(nlog(n)) in the best case and
Θ(n2log(n)) in the worst case.
*/