TExcelTAD
Home › Graph Algorithms › Dijkstra with Different Priority Queues

Dijkstra with Different Priority Queues

Dijkstra's algorithm performs three kinds of priority-queue operations: VV INSERTs (or one build), VV EXTRACT-MINs and at most EE 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

T(V,E)=V⋅Tinsert+V⋅Textract-min+E⋅Tdecrease-keyT(V, E) = V \cdot T_{\text{insert}} + V \cdot T_{\text{extract-min}} + E \cdot T_{\text{decrease-key}}
Priority queue EXTRACT-MIN DECREASE-KEY Dijkstra
unsorted array indexed by vertex O(V)O(V) O(1)O(1) O(V2+E)=O(V2)O(V^2 + E) = O(V^2)
binary heap O(lg⁡V)O(\lg V) O(lg⁡V)O(\lg V) O((V+E)lg⁡V)O((V + E) \lg V)
binary heap, lazy deletion (no decrease-key) O(lg⁡E)O(\lg E) push: O(lg⁡E)O(\lg E) O((V+E)lg⁡V)O((V + E) \lg V)
dd-ary heap O(dlog⁡dV)O(d \log_d V) O(log⁡dV)O(\log_d V) O((Vd+E)log⁡dV)O((Vd + E) \log_d V)
Fibonacci heap O(lg⁡V)O(\lg V) amortized O(1)O(1) amortized O(E+Vlg⁡V)O(E + V \lg V)
buckets, integer weights ≤C\le C scan forward to the next non-empty bucket O(1)O(1) O(VC+E)O(VC + E)

Some consequences:

  • Dense graphs (E=Θ(V2)E = \Theta(V^2)): the array's O(V2)O(V^2) is optimal, since the input itself has size Θ(V2)\Theta(V^2), and beats the binary heap's O(V2lg⁡V)O(V^2 \lg V).
  • Sparse graphs (E=O(V)E = O(V)): the binary heap's O(Vlg⁡V)O(V \lg V) beats the array's O(V2)O(V^2) by a wide margin.
  • A dd-ary heap with d=⌈E/V⌉d = \lceil E / V \rceil gives O(Elog⁡E/VV)O(E \log_{E/V} V), which is O(E)O(E) whenever E=V1+εE = V^{1 + \varepsilon} for a constant ε>0\varepsilon > 0. 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, O(E+Vlg⁡V)O(E + V \lg V), 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 0,1,2,…0, 1, 2, \ldots and scan the lists in order. Distances never exceed (V−1)C(V - 1)C.

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.

python · try it yourself
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 EE edges once; the differences are in the queue work on top. On the sparse graph the array version pays about V2=2.25V^2 = 2.25 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 V2+EV^2 + E, 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 (i,j)(i, j) has weight (j−i)2(j - i)^2). The heap's O(Elg⁡V)O(E \lg V) is a worst case that needs keys to climb the full height of the heap again and again; the array's O(V2)O(V^2) 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 (V−1)⋅10+1(V - 1) \cdot 10 + 1 buckets to scan; on the third graph, with weights up to 1992199^2, 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 EE entries instead of VV, and the program counts both the work and the peak size of the two versions on the sparse graph.

python · try it yourself
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 E≈12,000E \approx 12{,}000. 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 O(lg⁡V)O(\lg V). The set never holds more than VV entries. The program runs it on the road network of the Dijkstra lesson.

cpp · try it yourself
#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 E=Θ(V2)E = \Theta(V^2). Which priority queue gives the best bound among array and binary heap?

  1. Binary heap: O(V2lg⁡V)O(V^2 \lg V)
  2. Array: O(V2)O(V^2)
  3. They are equal
  4. Neither works on dense graphs

What is Dijkstra's running time with a Fibonacci heap?

  1. O(Elg⁡V)O(E \lg V)
  2. O(V2)O(V^2)
  3. O(E+Vlg⁡V)O(E + V \lg V)
  4. O(V+E)O(V + E)

Why does a dd-ary heap with large dd suit Dijkstra on graphs with many edges per vertex?

  1. It makes EXTRACT-MIN constant time
  2. It lowers the cost of the frequent DECREASE-KEY (O(log⁡dV)O(\log_d V)) at the expense of the rarer EXTRACT-MIN (O(dlog⁡dV)O(d \log_d V))
  3. It avoids lazy deletion
  4. It sorts the edges

With integer weights between 1 and CC, what is the running time of the bucket version (Dial's algorithm)?

  1. O(Elg⁡V)O(E \lg V)
  2. O(VC+E)O(VC + E)
  3. O(C2)O(C^2)
  4. O(V+E)O(V + E) always