Time complexity of Prim's MST algorithm is O(|V|^2)
if you use adjacency matrix representation.
I am trying to implement Prim's algorithm using adjacency matrix. I am using this as a reference.
V = {1,2...,n}
U = {1}
T = NULL
while V != U:
/*
Now this implementation means that
I find lowest cost edge in O(n).
How do I do that using adjacency list?
*/
let (u, v) be the lowest cost edge
such that u is in U and v is in V - U;
T = T + {(u,v)}
U = U + {v}
EDIT:
I WANT THE INEFFICIENT IMPLEMENTATION
Step 1: Determine the arbitrary starting vertex. Step 2: Keep repeating steps 3 and 4 until the fringe vertices (vertices not included in MST)remain. Step 3: Select an edge connecting the tree vertex and fringe vertex having the minimum weight. Step 4: Add the chosen edge to MST if it doesn't form any closed cycle.
The time complexity of the Prim's Algorithm is O ( ( V + E ) l o g V ) because each vertex is inserted in the priority queue only once and insertion in priority queue take logarithmic time.
The steps for implementing Prim's algorithm are as follows: Initialize the minimum spanning tree with a vertex chosen at random. Find all the edges that connect the tree to new vertices, find the minimum and add it to the tree. Keep repeating step 2 until we get a minimum spanning tree.
Finding the lowest cost edge (u,v), such that u is in U and v is in V-U, is done with a priority queue. More precisely, the priority queue contains each node v from V-U together with the lowest cost edge from v into the current tree U. In other words, the queue contains exactly |V-U| elements.
After adding a new node u to U, you have to update the priority queue by checking whether the neighboring nodes of u can now be reached by an edge of lower cost than previously.
The choice of priority queue determines the time complexity. You will get O(|V|^2) by implementing the priority queue as a simply array cheapest_edges[1..|V|]
. That's because finding minimum in this queue takes O(|V|) time, and you repeat that |V| times.
In pseudo-code:
V = {2...,n}
U = {1}
T = NULL
P = array, for each v set P[v] = (1,v)
while V != U
(u,v) = P[v] with v such that length P[v] is minimal
T = T + {(u,v)}
U = U + {v}
for each w adjacent to v
if length (v,w) < length P[w] then
P[w] = (v,w)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With