Can you impove Dijkstra's time complexity by not filling completely the priority queue?
I have found two diferent aproaches to Dijkstra's priority queue.
Shouldn't the time complexities be different?
Normal implementation of Dijkstra with priority queue
The implementation you usually find for Dijkstra's shortest path starts filling the priority queue with ALL vertices:
(From wikipedia's pseudocode:)
for each vertex v in Graph:
dist[v] ← INFINITY
prev[v] ← UNDEFINED
add v to Q
dist[source] ← 0
[...]
However, as said in The Big O on the Dijkstra Fibonacci-heap solution, the complexity of Dijkstra's shortest path algorithm is:
O(|E| |decrease-key(Q)| + |V| |extract-min(Q)|)
Using a binary heap as priority queue that is equal to: O((E + V)log(Q))
as decrease-key(Q) and extract-min(Q) are both O(log(|Q|))
Or if you fill the queue with all vertices: O((E+V)log(V))
Faster? implementation of Dijkstra with priority queue
The implementation found in python's networkx package, however, doesn't fill the priority queue with all vertices. It starts only with the source vertex and continues to insert other vertices as they are discovered. Something like:
Q = priority queue
seen = provisional distances to every 'seen' vertex
add source to Q
seen[source] ← 0
while Q not empty:
v = pop(Q)
if v == target -> path found!
for neig in neighbours of v:
if neig not in seen:
add neig to Q
...
[normal Dijksta algorithm]
This way the priority queue never even comes close to having |V| elements (in a relatively sparce graph at least). It will have at any given point all vertices in the boundary between explored and unseen vertices. Comparing with the "normal" implementation of the queue (Q1) this queue's (Q2) size will be: |Q2| = |Q1 where cost != inf|
My question
Wouldn't that mean the time complexity of this implementation is lower than O((E+V)log(V))
?
Am I missing something?
I have tested it in a road network graph and indeed it takes less time to compute a shortest path this way. Even excluding the time spent in filling the queue initialy in the "normal" case.