Dijkstra with Different Priority Queues
Dijkstra's algorithm performs three kinds of priority-queue operations: INSERTs (or one build), EXTRACT-MINs and at most DECREASE-KEYs. How long it takes depends entirely on what those operations cost, and the best queue depends on the graph. This lesson works out the running time for five queues, from a plain array to buckets for integer weights, and counts their elementary steps on sparse and dense graphs.
The cost formula
Each vertex is extracted once, and each edge causes at most one DECREASE-KEY, so
| Priority queue | EXTRACT-MIN | DECREASE-KEY | Dijkstra |
|---|---|---|---|
| unsorted array indexed by vertex | |||
| binary heap | |||
| binary heap, lazy deletion (no decrease-key) | push: | ||
| -ary heap | |||
| Fibonacci heap | amortized | amortized | |
| buckets, integer weights | scan forward to the next non-empty bucket |
Some consequences:
- Dense graphs (): the array's is optimal, since the input itself has size , and beats the binary heap's .
- Sparse graphs (): the binary heap's beats the array's by a wide margin.
- A -ary heap with gives , which is whenever for a constant . Its sift-down is more expensive, its sift-up cheaper: exactly the right trade, because Dijkstra does many more decrease-keys than extractions.
- The Fibonacci heap achieves the best general bound, , but its constant factors are large, so binary or 4-ary heaps usually win in practice.
- Buckets (Dial's algorithm) exploit small integer weights: keep a list of vertices for every possible distance and scan the lists in order. Distances never exceed .
The priority-queue lesson of Sorting & Order Statistics builds the binary heap; Prim's algorithm has the same operation profile and the same table.
Counting the steps
The program implements four of the queues and counts their elementary steps: array cells scanned, heap levels traversed (one per comparison-and-swap step), and buckets scanned. It runs them on a sparse and a dense random graph with weights from 1 to 10 and checks that all return the same distances.
import heapq, random
def random_graph(rng, n, m, C):
adj = [[] for _ in range(n)]
for i in range(n - 1):
adj[i].append((i + 1, rng.randint(1, C))) # a path keeps everything reachable
for _ in range(m - (n - 1)):
u, v = rng.randrange(n), rng.randrange(n)
if u != v:
adj[u].append((v, rng.randint(1, C)))
return adj
def with_array(adj, s):
n, INF = len(adj), float("inf")
d, done, steps = [INF] * n, [False] * n, 0
d[s] = 0
for _ in range(n):
u, best = -1, INF
for v in range(n): # scan for the minimum
steps += 1
if not done[v] and d[v] < best:
u, best = v, d[v]
if u < 0:
break
done[u] = True
for v, w in adj[u]:
steps += 1 # look at the edge
if d[u] + w < d[v]:
d[v] = d[u] + w
return d, steps
class DaryHeap:
def __init__(self, n, d):
self.k, self.a, self.pos, self.key, self.steps = d, [], [-1] * n, [0] * n, 0
def _swap(self, i, j):
a = self.a
a[i], a[j] = a[j], a[i]
self.pos[a[i]], self.pos[a[j]] = i, j
def _up(self, i):
while i > 0:
p = (i - 1) // self.k
self.steps += 1
if self.key[self.a[p]] <= self.key[self.a[i]]:
return
self._swap(i, p); i = p
def _down(self, i):
n = len(self.a)
while True:
first = self.k * i + 1
if first >= n:
return
kids = range(first, min(first + self.k, n))
self.steps += len(kids) # compare all children
c = min(kids, key=lambda j: self.key[self.a[j]])
if self.key[self.a[c]] >= self.key[self.a[i]]:
return
self._swap(i, c); i = c
def push_or_decrease(self, v, key):
self.key[v] = key
if self.pos[v] < 0:
self.a.append(v); self.pos[v] = len(self.a) - 1
self._up(self.pos[v])
def pop(self):
top = self.a[0]
self._swap(0, len(self.a) - 1)
self.a.pop(); self.pos[top] = -2 # -2 = extracted
if self.a:
self._down(0)
return top
def with_heap(adj, s, arity):
n, INF = len(adj), float("inf")
d = [INF] * n; d[s] = 0
h = DaryHeap(n, arity)
h.push_or_decrease(s, 0)
looks = 0
while h.a:
u = h.pop()
for v, w in adj[u]:
looks += 1
if h.pos[v] != -2 and d[u] + w < d[v]:
d[v] = d[u] + w
h.push_or_decrease(v, d[v])
return d, looks + h.steps
def with_buckets(adj, s, C):
n, INF = len(adj), float("inf")
C = max(w for a in adj for _, w in a)
d, done, steps = [INF] * n, [False] * n, 0
d[s] = 0
buckets = [[] for _ in range((n - 1) * C + 1)]
buckets[0].append(s)
for b in range(len(buckets)):
steps += 1 # look at bucket b
for u in buckets[b]:
if done[u] or d[u] != b:
continue # stale entry
done[u] = True
for v, w in adj[u]:
steps += 1
if d[u] + w < d[v]:
d[v] = d[u] + w; buckets[d[v]].append(v)
return d, steps
def worst_case(n):
# edge (i, j) for i < j with weight (j - i)^2: every edge lowers an estimate
return [[(j, (j - i) ** 2) for j in range(i + 1, n)] for i in range(n)]
rng = random.Random(14)
C = 10
for name, n, m in [("sparse", 1500, 6000), ("dense", 200, 20000), ("dense, every edge decreases", 200, None)]:
adj = random_graph(rng, n, m, C) if m else worst_case(n)
m = sum(len(a) for a in adj)
results = {"array": with_array(adj, 0), "binary heap": with_heap(adj, 0, 2), "8-ary heap": with_heap(adj, 0, 8)}
if max(w for a in adj for _, w in a) <= C:
results["buckets"] = with_buckets(adj, 0, C)
assert len({tuple(r[0]) for r in results.values()}) == 1 # all agree
print(f"{name}: V = {n}, E = {m}")
for label, (_, steps) in results.items():
print(f" {label:12} {steps:>10,} steps")sparse: V = 1500, E = 5996
array 2,255,996 steps
binary heap 30,517 steps
8-ary heap 40,252 steps
buckets 20,987 steps
dense: V = 200, E = 19891
array 59,891 steps
binary heap 21,792 steps
8-ary heap 22,729 steps
buckets 21,882 steps
dense, every edge decreases: V = 200, E = 19900
array 59,900 steps
binary heap 41,662 steps
8-ary heap 42,795 steps
Every version looks at all edges once; the differences are in the queue work on top. On the sparse graph the array version pays about million scans, while the heaps finish in 30,000 to 40,000 steps, most of them the edge looks themselves. On the dense graphs the array pays , and the heaps are still cheaper in these runs. The reason is that a DECREASE-KEY moves a vertex up only as far as its new key overtakes its ancestors, and here keys rarely overtake anything, even in the third graph, built so that every edge causes a decrease-key (edge has weight ). The heap's is a worst case that needs keys to climb the full height of the heap again and again; the array's is what it always costs. The 8-ary heap compares 8 children per level when it extracts, which only pays off when decrease-keys are both frequent and expensive. Buckets are cheapest on the random graphs because the weights are at most 10, so there are only buckets to scan; on the third graph, with weights up to , they would be hopeless, and the program skips them.
Decrease-key versus lazy deletion
heapq has no DECREASE-KEY, so Python programs usually push duplicates. The heap then holds up to entries instead of , and the program counts both the work and the peak size of the two versions on the sparse graph.
import heapq, random
rng = random.Random(14)
n, m, C = 3000, 12000, 10
adj = [[] for _ in range(n)]
for i in range(n - 1):
adj[i].append((i + 1, rng.randint(1, C)))
for _ in range(m - (n - 1)):
u, v = rng.randrange(n), rng.randrange(n)
if u != v:
adj[u].append((v, rng.randint(1, C)))
def lazy(adj, s):
d, done, pq = [float("inf")] * len(adj), [False] * len(adj), [(0, s)]
d[s] = 0
pushes = pops = stale = peak = 0
while pq:
peak = max(peak, len(pq))
du, u = heapq.heappop(pq); pops += 1
if done[u]:
stale += 1; continue
done[u] = True
for v, w in adj[u]:
if du + w < d[v]:
d[v] = du + w
heapq.heappush(pq, (d[v], v)); pushes += 1
return d, pushes, pops, stale, peak
d, pushes, pops, stale, peak = lazy(adj, 0)
print(f"lazy deletion: {pushes} pushes, {pops} pops, {stale} stale entries skipped, peak heap size {peak}")
print(f"an indexed heap would hold at most {n} entries and do {n} extractions")lazy deletion: 3719 pushes, 3720 pops, 720 stale entries skipped, peak heap size 1606
an indexed heap would hold at most 3000 entries and do 3000 extractions
About a fifth of the pops are stale, and the peak heap size, 1606, stays far below . In practice lazy deletion is simple and fast, which is why the standard libraries of Python, C++ and Java offer heaps without DECREASE-KEY.
In C++
A std::set of (distance, vertex) pairs is an ordered structure that supports DECREASE-KEY directly: erase the old pair and insert the new one, both . The set never holds more than entries. The program runs it on the road network of the Dijkstra lesson.
#include <climits>
#include <cstdio>
#include <set>
#include <utility>
#include <vector>
int main() {
const int n = 7;
std::vector<std::vector<std::pair<int, int>>> adj(n);
auto add = [&](char u, char v, int w) {
adj[u - 'A'].push_back({v - 'A', w});
adj[v - 'A'].push_back({u - 'A', w});
};
add('A','B',4); add('A','C',2); add('B','C',1); add('B','D',5); add('C','D',8); add('C','E',10);
add('D','E',2); add('D','F',6); add('E','F',2); add('E','G',7); add('F','G',3);
std::vector<long long> d(n, LLONG_MAX);
std::set<std::pair<long long, int>> q; // ordered by (distance, vertex)
d[0] = 0;
q.insert({0, 0});
int decreases = 0;
std::printf("settle order:");
while (!q.empty()) {
auto [du, u] = *q.begin();
q.erase(q.begin());
std::printf(" %c(%lld)", 'A' + u, du);
for (auto [v, w] : adj[u])
if (du + w < d[v]) {
if (d[v] != LLONG_MAX) { q.erase({d[v], v}); ++decreases; } // decrease-key
d[v] = du + w;
q.insert({d[v], v});
}
}
std::printf("\n%d decrease-key operations\n", decreases);
}settle order: A(0) C(2) B(3) D(8) E(10) F(12) G(15)
5 decrease-key operations
Test yourself
Dijkstra runs on a dense graph with . Which priority queue gives the best bound among array and binary heap?
- Binary heap:
- Array:
- They are equal
- Neither works on dense graphs
What is Dijkstra's running time with a Fibonacci heap?
Why does a -ary heap with large suit Dijkstra on graphs with many edges per vertex?
- It makes EXTRACT-MIN constant time
- It lowers the cost of the frequent DECREASE-KEY () at the expense of the rarer EXTRACT-MIN ()
- It avoids lazy deletion
- It sorts the edges
With integer weights between 1 and , what is the running time of the bucket version (Dial's algorithm)?
- always