I am using an adjacency matrix, priority queue is the data structure.
By my calculation, complexity is V^3 log V:
- While loop:
V - Checking adjacent Vertices:
V - Checking the queue if the entry is already present, and updating the same:
V log v
But, I read everywhere that the complexity is V^2
Please explain.
If you use a Fibonacci heap, then extracting the min is
O(lg V)amortized cost and updating an entry in it isO(1)amortized.If we use this pseudo code
Assume that the implementation has constant time for both
priorityQueue.contains(v)andneedsWeightReduction(u, v).Something to note is that you can bound slightly tighter for checking adjacencies. While the outer loop runs
Vtimes, and checking the adjacencies of any single node is at worstVoperations, you can use aggregate analysis to realize that you will never check for more thanEadjacencies(because theres only E edges). AndE <= V^2, so this is a slightly better bound.So, you have the outer loop V times, and the inner loop E times. Extracting the min runs
Vtimes, and updating an entry in the heap runsEtimes.Again, since
E <= V^2you could use this fact to substitute and getBut this is a looser bound when considering sparse graphs(although correct).