Can someone explain to me why is Prim’s Algorithm using adjacent matrix result in a time complexity of O(V2)?
Can someone explain to me why is Prim’s Algorithm using adjacent matrix result in
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
(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 itdistancewhich has the minimum distance of that vertex to the node.This way, we only ever check
distanceto find the next target, and since we do this V times and there are V members ofdistance, our complexity isO(V^2).This on it’s own wouldn’t be enough as the original values in
distancewould 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 thedistanceappropriately. This doesn’t affect our time complexity since it merely means that each step takesO(V+V) = O(2V) = O(V). Therefore our algorithm isO(V^2).Without using
distancewe have to iterate through all E edges every single time, which at worst contains V^2 edges, meaning our time complexity would beO(V^3).Proof:
To prove that without the
distancearray it is impossible to compute the MST inO(V^2)time, consider that then on each iteration with a tree of sizen, there areV-nvertices 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:
QED