Time complexity of Prim's MST Algorithm

U.f.O picture U.f.O · Oct 30, 2012 · Viewed 8.7k times · Source

Can someone explain to me why is Prim's Algorithm using adjacent matrix result in a time complexity of O(V2)?

Answer

Daniel Gratzer picture Daniel Gratzer · Oct 30, 2012

(Sorry in advance for the sloppy looking ASCII math, I don't think we can use LaTEX to typeset answers)

The traditional way to implement Prim's algorithm with O(V^2) complexity is to have an array in addition to the adjacency matrix, lets call it distance which has the minimum distance of that vertex to the node.

This way, we only ever check distance to find the next target, and since we do this V times and there are V members of distance, our complexity is O(V^2).

This on it's own wouldn't be enough as the original values in distance would quickly become out of date. To update this array, all we do is at the end of each step, iterate through our adjacency matrix and update the distance appropriately. This doesn't affect our time complexity since it merely means that each step takes O(V+V) = O(2V) = O(V). Therefore our algorithm is O(V^2).

Without using distance we have to iterate through all E edges every single time, which at worst contains V^2 edges, meaning our time complexity would be O(V^3).

Proof:

To prove that without the distance array it is impossible to compute the MST in O(V^2) time, consider that then on each iteration with a tree of size n, there are V-n vertices to potentially be added.

To calculate which one to choose we must check each of these to find their minimum distance from the tree and then compare that to each other and find the minimum there.

In the worst case scenario, each of the nodes contains a connection to each node in the tree, resulting in n * (V-n) edges and a complexity of O(n(V-n)).

Since our total would be the sum of each of these steps as n goes from 1 to V, our final time complexity is:

(sum O(n(V-n)) as n = 1 to V) =  O(1/6(V-1) V (V+1)) = O(V^3)

QED