I was studying Dijkstra algorithm code given at this link -> https://java2blog.com/dijkstra-java/
Can someone explain the following 2 parts of the code?
1) Why a
To begin with, this code is bad, since priorityQueue.remove(v)
requires O(n) time, which defeats the whole purpose of using PriorityQueue
https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/PriorityQueue.html:
... linear time for the remove(Object) ...
2) Dijkstra's algorithm in one phrase: select a non-visited vertex with a smallest distance
. To extract the vertex with a smallest distance, you maintain a priority queue, where you compare vertices by distance (this is what your compareTo
does). So the vertex which is extracted will be the vertex with the smallest distance.
1) Data structures have some assumptions. If these assumptions are violated, data structures may work incorrectly. In case of PriorityQueue
the assumption is "for any elements in the queue the result of comparison doesn't change". And, since you compare using distance
, if you change the distance
, then the result of comparison may also change, leaving your PriorityQueue
in potentially invalid state. Therefore, you first remove the element, and only after that change the distance.