(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")
  1. 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.
  2. 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".
  3. 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.
  4. Create an empty set of edges, MST.
  5. 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.*/

  6. FOR j = 2 to n,
    /* Note: Initializations in step 6 do Θ(nlog(n)) work.*/

  7. WHILE PQ is not empty DO

/* 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. */