Prim’s algorithm
This solves the MST problem using a method similar to Dijkstra’s algorithm. It will use a Priority queue to do this.
Algorithm
Prim's(G,w):
Input: undirected graph G=(V,E) with weights w(e).
Output: MST defined by the array prev
for all u in V
cost(u) = inf
prev(u) = nil
Pick any initial node u_0
cost(u_0) = 0
H = makequeue(V)
while H is not empty:
v = deletemin(H)
for each {v,z} in E:
if cost(z) > w(v,z):
cost(z) = w(v,z)
prev(z) = v
decreasekey(H,z)
output prev
Correctness
Note that functionally Prim’s algorithm is slowly building a tree
We prove by induction on the size of
Base case
Note there must be an MST
Induction case
Suppose
Suppose we find the next closest vertex
Therefore by the cut property
This proves the induction case and we have that
Conclusion
As the algorithm runs until each vertex is added to the tree
Run time
Initialisation takes
To fetch the key
We iterate over each edge twice and for each iteration we might have to call decreasekey which takes
All together this takes