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.
1) PriorityQueue only evaluates priority when entries are inserted. Just changing the priority on v
will not cause this evaluation, so it will have no effect.
2) The basic contract for compareTo
is that it returns 0 iff both instances or considered equal. 1 if this is considered "bigger" -1 if this is considered "smaller". Double.compare(..)
creates this semantic for a Double
value.