Priority queues and heaps
Priority queues power Dijkstra, Prim, Huffman, schedulers and top-k. Implement a binary heap in an array, prove linear-time construction, add decrease-key with a position index, and study d-ary, meldable and Fibonacci heaps with potential analysis.
After this lesson you can
- Implement a binary heap in an array and prove sift-up and sift-down correctness.
- Prove bottom-up construction costs O(n) by summing heights.
- Implement decrease-key with a position index and compare it with heapq's lazy strategy.
- Choose heap arity according to the proportion of decrease-key and extract-min operations.
- Explain Fibonacci heaps' amortized analysis and why they rarely win in practice.
Before you start
Motivation: always the next most urgent
Many programs repeatedly ask the same question: among all pending items, which is most urgent? Usually we need only the next item, not the complete ordering.
- Event simulation. A simulator maintains future events, each with its time. At each step it extracts the nearest, executes it and may schedule new events. Sorting all events does not work: they appear during execution.
- Merging sorted streams. To merge sorted files (database compaction or the merge phase of external sorting), inspect the smallest of the heads. Advance the stream supplying it and inspect again.
- Shortest paths and spanning trees. Dijkstra and Prim extract the nearest vertex and, when exploring it, decrease neighbors’ distances. They need a queue whose keys can decrease.
- The largest items in a stream. A search engine seeking the best results among millions of candidates cannot keep them all: it maintains the best so far and compares each candidate with the worst of them.
- Codes and search. Huffman repeatedly extracts the two least likely symbols, BPE training needs the most frequent pair at each merge, and uniform-cost search and A* expand the most promising node.
The structure that solves this is a priority queue, and its canonical implementation, the heap, fits in an array without a single pointer. This lesson has three threads. First, what to expect of a priority queue and why no design can be too fast. Second, the binary heap and its details: linear-time construction, sorting, changing keys and choosing arity. Third, structures trading complexity for cheaper meld and decrease-key, up to the Fibonacci heap, an opportunity to use the potential method on a real structure.
The priority queue as an abstract type
A max queue reverses the order (in practice, negate keys). If multiple elements share the minimum key, the specification allows returning any one: tie order is not guaranteed, so include it in the key if needed (as we will see with heapq). A priority queue is an interface: an unsorted array gives insert for and extract-min for ; a sorted array reverses these costs; a heap balances them. The natural question is how much that balance can be improved.
Proof
The queue sorts any list of distinct keys: insert all and extract them one by one, producing sorted output. This is a comparison sort costing . By the sorting lower bound, its decision tree has at least leaves and therefore depth at least . The second inequality is .
∎This bound has three consequences. A heap with insert and extract-min in is optimal up to constants. insert can be amortized (as in Fibonacci heaps), but then extract-min must cost amortized. And Dijkstra, extracting vertices in increasing distance, sorts them by distance: no comparison algorithm delivering that order can beat , making the bound with Fibonacci heaps optimal for that family. Computing distances without sorting vertices is another problem, where the barrier has been broken: Duan, Mao, Mao, Shu and Yin (2025) solve it on directed graphs in , better than on sparse graphs. The sorting bound does not constrain decrease-key, which occupies half this lesson.
The relationship also works in reverse. On a word RAM (integer keys and machine-word operations), Thorup (2007) showed that if keys can be sorted in time , there is a priority queue with insert and extract-min in : priority queues and sorting are, up to constants, the same problem.
The binary heap in an array
The tree’s complete shape is not stored: indices determine it. Thus a heap needs no pointers, occupies exactly cells and traverses contiguous memory. Heap order is much weaker than search-tree order: each node is no greater than its children, with no relation between siblings. Consequently the minimum is always at and an arbitrary value cannot be searched for without scanning everything.
How tall is the tree? If its last level is , levels are full and contain nodes, while level has between and . Thus , that is:
Operation cost is therefore a multiple of : with a million elements, . The first interactive shows the same structure both ways at once; each item moves with its swap in the tree and array.
Sift up and sift down
Every heap operation locally repairs order. There are only two movements.
- Sift up (
sift-up) position : while and , swap them. Used afterinsert(the new element enters the first free position, ) and afterdecrease-key. - Sift down (
sift-down) position : while has a child smaller than , swap it with its smaller child. Used afterextract-min(the last element takes the root) and in construction.
Using the smaller child matters: it alone can take the parent’s place without violating order with its sibling.
Proof
Let , , and suppose . After the swap, and . Four edges change.
- : , so it holds.
- for each child of : by the second hypothesis, so it holds.
- with the sibling of : before, (an edge other than that of ), and now .
- : the only edge that may fail, entering the new position .
The second condition remains for new position : its children are now (containing ) and . Edge held before the swap because , so ; also . Thus exceeds neither child of . If there is no swap and the only doubtful edge, , holds. If there is no incoming edge and the hypothesis says it is already a heap.
∎Sift-up terminates because decreases, after at most swaps. When insert puts the new element at position , the second condition is vacuous (it has no children) and all other edges already held; the lemma guarantees a heap. Sift-down is the mirror image: the invariant says order holds except possibly on edges from to its children and that for both children ; if the smaller child satisfies , swapping restores the invariant with . The proof is the lemma’s with roles reversed.
Counting comparisons: insert and decrease-key make at most (one per level). extract-min makes at most : per level, compare the two children to find the smaller, then compare that child with the sinking element. With these are and . If the array grows, use dynamic-array doubling, adding amortized to each insert without changing the above. There is a pleasant surprise for insert: although worst case is , randomly ordered keys barely sift up (in the cells below, about swaps per insertion), because most elements belong to the last level and are rarely the smallest in their branch.
Linear-time construction
Given any array of elements, what does turning it into a heap cost? The obvious option is to insert the elements one at a time. In the worst case (decreasing keys, each rising to the root) this costs swaps.
Floyd (1964) observed that we can go the other way: bottom-up, sifting down. Leaves are already one-element heaps; the last internal node is . Traversing positions from there to and sifting each down makes each subtree a heap with both children already prepared.
Correctness follows from a simple invariant: before sifting down position , every position roots a subtree that is already a heap. The children of satisfy , so the sift-down lemma’s hypothesis holds within the subtree of , which has no parent; after sifting, the subtree of is a heap. On reaching , the whole array is one.
The surprising part is cost. Sifting a node down costs, in the worst case, as many swaps as its height (distance to the deepest leaf in its subtree), not its depth. Many tree nodes are close to leaves.
Proof
For node , the longest path to a leaf always descends through the left child (the tree fills from the left), and the index of the descendant levels down that path is . That descendant exists if and only if , that is, . Thus
Summing by layers, . This sum is the exponent of in (Legendre’s formula), equal to . For comparisons: each level a node descends costs at most two comparisons, and if it stops before reaching a leaf it makes two more, but then it has descended fewer levels than its height. In either case, sifting down costs at most comparisons, and the sum over nodes is .
∎The idea is a power sum: with nodes, half are leaves (work ), a quarter have height (work ), an eighth height , and so on. Work per height level decreases as height grows, and the sum converges to . With insertions, by contrast, the largest level (the bottom) pays the most work: each last-level node can rise levels.
And is optimal, since building a heap requires looking at every element. heapq.heapify, std::make_heap and their equivalents in other languages use bottom-up construction (CPython with the sift-down variant in the heapsort section).
Heapsort
With a heap, sorting is immediate: build it in and perform extractions of .
Its cost is always , including the worst case; it uses extra memory, is unstable and does not adapt to nearly sorted input. This makes it unique among classic fast sorts: neither quicksort (quadratic worst case) nor mergesort (linear memory) has both worst-case and constant space. Hybrid sorts (introsort) therefore use heapsort as a safety net when partitioning degrades.
Count comparisons: each extraction sifts down levels with 2 comparisons per level, so heapsort makes on the order of in the worst case. The lower bound is : a factor from optimal. A variant fixes this (Carlsson, 1987; Wegener, 1993): while sifting the root down, move the hole down via the smaller child with one comparison per level to a leaf, then sift the element up from there to its place. The sinking element came from a leaf and almost always ends near one, so the upward path is short. With this variant measured comparisons fall to nearly , as the cells show. CPython uses it in heapq.
Why does quicksort win in practice? The reason is the machine, rather than comparison count. Quicksort partitioning traverses the array sequentially, exploiting cache and memory prefetching. Heapsort sifting jumps from to : at lower levels each step touches a different cache line, and comparison between children is an unpredictable branch. For arrays that do not fit in cache, these misses dominate.
This cell measures the two numerical claims in the previous sections. It counts swaps for both heap construction methods on decreasing (worst-case) and random input, and heapsort comparisons with classic and bottom-up sifting.
import math, random
def hundir(a, i, n, cnt):
"""Hunde a[i] en un montículo de MÍNIMO de n elementos. cnt = [comparaciones, intercambios]."""
while 2 * i + 1 < n:
c = 2 * i + 1
if c + 1 < n:
cnt[0] += 1
if a[c + 1] < a[c]:
c += 1
cnt[0] += 1
if a[c] < a[i]:
a[i], a[c] = a[c], a[i]
cnt[1] += 1
i = c
else:
break
def construir_floyd(a):
cnt = [0, 0]
for i in range(len(a) // 2 - 1, -1, -1): # los nodos internos, del último al primero
hundir(a, i, len(a), cnt)
return cnt
def construir_inserciones(valores):
a, cnt = [], [0, 0]
for v in valores:
a.append(v)
i = len(a) - 1
while i > 0:
cnt[0] += 1
if a[i] < a[(i - 1) // 2]:
a[i], a[(i - 1) // 2] = a[(i - 1) // 2], a[i]
cnt[1] += 1
i = (i - 1) // 2
else:
break
return cnt
random.seed(7)
print(f"{'n':>7} {'Floyd peor':>11} {'n - bits(n)':>12} {'Floyd azar':>11} {'ins. peor':>10} {'ins. azar':>10} {'n log2 n':>9}")
for n in [15, 127, 1023, 8191, 65535]:
peor = list(range(n, 0, -1)) # orden decreciente: todo nodo cae hasta una hoja o sube hasta la raíz
azar = random.sample(range(n), n)
fp = construir_floyd(peor[:])[1]
fa = construir_floyd(azar[:])[1]
ip = construir_inserciones(peor)[1]
ia = construir_inserciones(azar)[1]
print(f"{n:7d} {fp:11d} {n - bin(n).count('1'):12d} {fa:11d} {ip:10d} {ia:10d} {round(n * math.log2(n)):9d}")
# heapsort (montículo de máximo, en el sitio): comparaciones medidas frente a n log2 n
def hundir_max(a, i, n, cnt):
while 2 * i + 1 < n:
c = 2 * i + 1
if c + 1 < n:
cnt[0] += 1
if a[c + 1] > a[c]:
c += 1
cnt[0] += 1
if a[c] > a[i]:
a[i], a[c] = a[c], a[i]
i = c
else:
break
def hundir_hasta_hoja(a, i, n, cnt):
"""Variante ascendente: baja el hueco por el hijo mayor (1 comparación por nivel) y sube el elemento desde la hoja."""
x = a[i]
j = i
while 2 * j + 1 < n:
c = 2 * j + 1
if c + 1 < n:
cnt[0] += 1
if a[c + 1] > a[c]:
c += 1
a[j] = a[c]
j = c
while j > i:
cnt[0] += 1
p = (j - 1) // 2
if a[p] < x:
a[j] = a[p]
j = p
else:
break
a[j] = x
def heapsort(a, hundir):
cnt = [0]
n = len(a)
for i in range(n // 2 - 1, -1, -1):
hundir(a, i, n, cnt)
for fin in range(n - 1, 0, -1):
a[0], a[fin] = a[fin], a[0]
hundir(a, 0, fin, cnt)
return cnt[0]
print()
for n in [1000, 10000]:
datos = random.sample(range(10 * n), n)
a, b = datos[:], datos[:]
ca, cb = heapsort(a, hundir_max), heapsort(b, hundir_hasta_hoja)
assert a == b == sorted(datos)
print(f"n = {n:6d}: heapsort clásico {ca} comparaciones ({ca / (n * math.log2(n)):.2f} n log2 n), variante ascendente {cb} ({cb / (n * math.log2(n)):.2f} n log2 n), cota inferior log2(n!) = {round(math.lgamma(n + 1) / math.log(2))}")The “Floyd peor” column matches exactly (for , with ): bottom-up construction on decreasing input attains the theorem’s bound. Random input drops to about swaps. Insertions on decreasing input make (for , about times ), and on random input about : insertion builds a heap almost as well when data arrives randomly, but only bottom-up guarantees it. In the last two rows, classic heapsort makes between and comparisons on random input, and the bottom-up variant nearly ( or more), between and above the lower bound .
decrease-key: position index or lazy insertion
Dijkstra, Prim and A* need to decrease the key of an element already in the queue. In the heap array the element is no longer where we put it: it moves with swaps. Without an index it must be searched for, .
There are two subtleties. First, delete(x) is not simply “put the last element in the hole and sift down.” The element filling the hole comes from another branch and can be smaller than the hole’s parent, in which case it must sift up. In heap , deleting (position 3) replaces it with (the last), and : without sifting up, order breaks. Second, pos is a new invariant that must be maintained on every swap and checked in tests.
The index-free alternative is lazy insertion: modify nothing. To “decrease” the key of , insert a new entry while leaving the old one in the heap. On extraction, if an entry’s key does not match the best known for (dist[x]), it is stale and discarded. This is the usual way to use heapq in Dijkstra.
Neither changes the asymptotic order: the lazy heap contains up to entries (one per successful relaxation) instead of , but , so Dijkstra remains . With the index, the heap holds at most elements and there are decrease-key at cost , the same bound. Differences are in constants: the lazy version uses more memory and makes more extractions (stale entries), but avoids the index, updates to pos on each swap, and a custom heap written in Python instead of C. First you will implement the index.
import random
class MonticuloIndexado:
"""Cola de prioridad de mínimo con claves modificables.
heap[i] es el identificador que ocupa la posición i; pos[x] devuelve su posición; key[x], su clave."""
def __init__(self):
self.heap, self.pos, self.key = [], {}, {}
self.comparaciones = 0
def __len__(self):
return len(self.heap)
def _menor(self, i, j): # ¿clave en la posición i < clave en la posición j?
self.comparaciones += 1
return self.key[self.heap[i]] < self.key[self.heap[j]]
def _intercambiar(self, i, j):
h = self.heap
h[i], h[j] = h[j], h[i]
self.pos[h[i]], self.pos[h[j]] = i, j # el índice de posiciones se actualiza en cada intercambio
def _subir(self, i):
while i > 0 and self._menor(i, (i - 1) // 2):
self._intercambiar(i, (i - 1) // 2)
i = (i - 1) // 2
return i
def _hundir(self, i):
n = len(self.heap)
while 2 * i + 1 < n:
c = 2 * i + 1 # hijo izquierdo
if c + 1 < n and self._menor(c + 1, c):
c += 1 # el derecho es menor
if not self._menor(c, i):
break
self._intercambiar(i, c)
i = c
def insert(self, x, k):
self.key[x] = k
self.heap.append(x)
self.pos[x] = len(self.heap) - 1
self._subir(len(self.heap) - 1)
def find_min(self):
x = self.heap[0]
return x, self.key[x]
def decrease_key(self, x, k):
assert k <= self.key[x], "decrease_key solo baja la clave"
self.key[x] = k
self._subir(self.pos[x])
def delete(self, x):
i = self.pos[x]
ultimo = self.heap.pop()
del self.pos[x]
k = self.key.pop(x)
if i < len(self.heap): # x no era el último: el último ocupa su hueco
self.heap[i] = ultimo
self.pos[ultimo] = i
if self._subir(i) == i: # si no sube, quizá tenga que bajar
self._hundir(i)
return k
def extract_min(self):
x, k = self.find_min()
self.delete(x)
return x, k
def invariante(self):
h, p, k = self.heap, self.pos, self.key
return (all(k[h[(i - 1) // 2]] <= k[h[i]] for i in range(1, len(h)))
and all(p[x] == i for i, x in enumerate(h)) and len(p) == len(k) == len(h))
# 1) prueba aleatoria frente a un diccionario: tras cada operación, la invariante y el mínimo correcto
random.seed(1)
q, modelo, sig = MonticuloIndexado(), {}, 0
for paso in range(6000):
r = random.random()
if r < 0.40 or not modelo:
q.insert(sig, random.randint(0, 10**6)); modelo[sig] = q.key[sig]; sig += 1
elif r < 0.65:
x, k = q.extract_min()
assert k == min(modelo.values()) == modelo.pop(x)
elif r < 0.85:
x = random.choice(list(modelo)); k = random.randint(0, modelo[x])
q.decrease_key(x, k); modelo[x] = k
else:
x = random.choice(list(modelo)); assert q.delete(x) == modelo.pop(x)
assert q.invariante() and len(q) == len(modelo)
print("6000 operaciones al azar: invariante y mínimo correctos")
# 2) por qué delete necesita subir Y hundir: el último elemento viene de otra rama
q = MonticuloIndexado()
for x, k in enumerate([1, 10, 2, 11, 12, 3, 4]):
q.insert(x, k)
print("antes:", [q.key[x] for x in q.heap])
q.delete(3) # se borra la clave 11; el 4 ocupa su hueco, y 4 < 10 (su nuevo padre)
print("tras delete(clave 11):", [q.key[x] for x in q.heap], "invariante:", q.invariante())
# 3) fusionar k listas ordenadas con un montículo de k elementos
def fusionar(listas):
q = MonticuloIndexado()
sig = [0] * len(listas)
for j, l in enumerate(listas):
if l:
q.insert(j, l[0])
salida = []
while len(q):
j, v = q.extract_min()
salida.append(v)
sig[j] += 1
if sig[j] < len(listas[j]):
q.insert(j, listas[j][sig[j]])
return salida, q.comparaciones
k, N = 16, 20000
listas = [sorted(random.randint(0, 10**6) for _ in range(N // k)) for _ in range(k)]
mezcla, comps = fusionar(listas)
assert mezcla == sorted(sum(listas, []))
print(f"fusionar {k} listas ({N} elementos): {comps / N:.1f} comparaciones por elemento (cada extract-min usa ≈ 2·log2 k = 8)")
print(f" en total {comps}; ordenar todo de cero costaría ≈ N·log2 N = {round(N * 14.29)}")
# 4) los k mayores de un flujo, con memoria O(k)
def top_k(flujo, k):
q, comps_externas = MonticuloIndexado(), 0
for i, v in enumerate(flujo):
if len(q) < k:
q.insert(i, v)
else:
comps_externas += 1 # una sola comparación con el mínimo actual
if v > q.find_min()[1]:
q.extract_min()
q.insert(i, v)
return sorted((q.key[x] for x in q.heap), reverse=True), comps_externas + q.comparaciones
n, k = 200_000, 10
flujo = [random.random() for _ in range(n)]
res, comps = top_k(flujo, k)
assert res == sorted(flujo, reverse=True)[:k]
print(f"top-{k} de {n} elementos: {comps} comparaciones, solo un {100 * (comps - n) / n:.2f} % más que mirar cada elemento una vez; ordenar costaría ≈ {round(n * 17.6)}")Three results to retain. First, randomized testing with the invariant checked after every operation gives confidence in a stateful structure: two lists (heap and pos) must agree, and a bug may appear only when the last element comes from another branch. Second, merging streams costs , not : each element pays for heap size , not data size. Third, top- from a stream with a heap of size processes almost all elements with one comparison against the minimum: a new element enters the heap rarely (in random order, element enters with probability , for about entries total).
d-ary heaps
Nodes need not have two children. In a -ary heap, the children of are and its parent is .
The effect on costs is asymmetric. Sifting up is cheaper because there are levels, one comparison per level, and decreases as rises. Sifting down costs more per level: choose the smallest of children ( comparisons), then compare it with the sinking element (one more), so extract-min costs comparisons. Coefficient is minimized at : it is for , for and again for . and agree because . Thus, in extract-min comparisons, the -ary heap does not lose to binary while its tree is half as tall (for a million elements, levels versus ): decrease-key and insert cost half and the path touches half as many cache lines.
If each element undergoes on average decrease-key (in Dijkstra, in the worst case, one per edge), worst-case model cost per element is , and the best grows with .
Johnson (1975) turned this into a rule: with , Dijkstra and Prim cost . For with constant , this is : linear in edges using only an array and no Fibonacci heap. For it matches the linear-array algorithm, .
This is a worst-case model: it assumes every decrease-key rises through all levels. In practice almost none does. In a random graph with random weights Dijkstra’s expected number of decrease-key is (Noshita, 1985), much less than , and each usually rises only a few levels. The next cell measures this with an indexed -ary heap and lazy heapq.
import heapq, random, time
class MonticuloD:
"""Montículo d-ario indexado sobre identificadores 0..N-1. Cuenta comparaciones y movimientos."""
def __init__(self, d, N):
self.d, self.heap, self.pos, self.key = d, [], [-1] * N, [0.0] * N
self.comparaciones = self.movimientos = 0
def _subir(self, i):
h, pos, key, d = self.heap, self.pos, self.key, self.d
x = h[i]
while i > 0:
p = (i - 1) // d
self.comparaciones += 1
if key[x] < key[h[p]]:
h[i] = h[p]; pos[h[i]] = i # el padre baja un nivel (sin intercambio completo)
i = p
self.movimientos += 1
else:
break
h[i] = x; pos[x] = i
def _hundir(self, i):
h, pos, key, d = self.heap, self.pos, self.key, self.d
n, x = len(h), h[i]
while True:
primero = d * i + 1
if primero >= n:
break
c = primero
for j in range(primero + 1, min(primero + d, n)):
self.comparaciones += 1
if key[h[j]] < key[h[c]]:
c = j
self.comparaciones += 1
if key[h[c]] < key[x]:
h[i] = h[c]; pos[h[i]] = i
i = c
self.movimientos += 1
else:
break
h[i] = x; pos[x] = i
def insert(self, x, k):
self.key[x] = k
self.heap.append(x)
self._subir(len(self.heap) - 1)
def decrease_key(self, x, k):
self.key[x] = k
self._subir(self.pos[x])
def extract_min(self):
h = self.heap
x = h[0]
ultimo = h.pop()
if h:
h[0] = ultimo
self._hundir(0)
self.pos[x] = -1
return x
def grafo_aleatorio(n, m, semilla):
rnd = random.Random(semilla)
adj = [[] for _ in range(n)]
for v in range(1, n): # un camino aleatorio garantiza la conexión
u = rnd.randrange(v)
w = rnd.random() + 0.01
adj[u].append((v, w)); adj[v].append((u, w))
for _ in range(m - (n - 1)):
u, v = rnd.randrange(n), rnd.randrange(n)
w = rnd.random() + 0.01
adj[u].append((v, w)); adj[v].append((u, w))
return adj
def dijkstra_indexado(adj, s, d):
n = len(adj)
dist = [float("inf")] * n
dist[s] = 0.0
q = MonticuloD(d, n)
q.insert(s, 0.0)
decreases = 0
while q.heap:
u = q.extract_min()
for v, w in adj[u]:
if dist[u] + w < dist[v]:
if q.pos[v] == -1 and dist[v] == float("inf"):
dist[v] = dist[u] + w
q.insert(v, dist[v])
elif q.pos[v] != -1:
dist[v] = dist[u] + w
q.decrease_key(v, dist[v])
decreases += 1
return dist, q, decreases
def dijkstra_perezoso(adj, s):
dist = [float("inf")] * len(adj)
dist[s] = 0.0
cola, pushes, obsoletos = [(0.0, s)], 1, 0
while cola:
du, u = heapq.heappop(cola)
if du > dist[u]: # entrada obsoleta: ya había una mejor
obsoletos += 1
continue
for v, w in adj[u]:
if du + w < dist[v]:
dist[v] = du + w
heapq.heappush(cola, (dist[v], v))
pushes += 1
return dist, pushes, obsoletos
for n, m in [(4000, 12000), (1000, 20000)]:
adj = grafo_aleatorio(n, m, 3)
t0 = time.perf_counter(); ref, pushes, obs = dijkstra_perezoso(adj, 0); t_lazy = time.perf_counter() - t0
print(f"\ngrafo n = {n}, m = {m} (m/n = {m / n:.0f}). Perezoso con heapq: {pushes} inserciones, {obs} entradas obsoletas, {t_lazy * 1000:.0f} ms")
print(" d comparaciones movimientos decrease-key tiempo (ms)")
for d in (2, 3, 4, 8, 16):
t0 = time.perf_counter()
dist, q, dec = dijkstra_indexado(adj, 0, d)
t = time.perf_counter() - t0
assert all(abs(a - b) < 1e-9 for a, b in zip(dist, ref))
print(f"{d:4d} {q.comparaciones:13d} {q.movimientos:11d} {dec:12d} {t * 1000:10.0f}")The table confirms the extract-min analysis and somewhat challenges the worst case. The number of decrease-key is a fraction of or , not ; total comparisons are nearly equal for (minimum near ) and clearly rise for and , because cost is then dominated by extract-min of . What always decreases with is moves (lower height), which cost cache accesses on a real machine. This is why tuned implementations often prefer to (LaMarca and Ladner, 1996, study heap cache effects). The lazy version wins by a wide margin in Python despite more insertions and stale extractions because heapq is written in C. Measure your real workload: the worst-case optimum is not necessarily your program’s optimum.
Meldable heaps: binomial and pairing
For binary heaps, merging heaps of sizes and costs : concatenate the arrays and run build-heap. Some applications (scheduling tasks across processors, graph algorithms merging components) need cheap meld.
Binomial heaps: binary addition
A binomial tree of rank , , is defined recursively: is a node and is obtained by linking two , making one root a child of the other. By induction, has nodes, its root has degree and its children root (hence the name: at depth there are nodes). To link while maintaining heap order, attach the root with the larger key: one link costs .
A binomial heap with elements is a list of heap-ordered binomial trees, at most one of each rank, with rank present if and only if bit of equals . There is a unique heap shape for each , with at most trees.
meldis binary addition: traverse ranks from low to high and link two trees of the same rank whenever encountered, carrying a higher-rank tree. Cost .insertismeldwith a one-node heap: incrementing a binary counter, so consecutive insertions cost total (amortized ), by the counter’s amortized analysis.extract-minfinds the smallest among roots, removes it and performsmeldon its children (exactly , already a binomial heap): .decrease-keysifts up in its tree, whose height is : .
Pairing heaps: simplicity in exchange for difficult proofs
A pairing heap is a single heap-ordered tree with no prescribed shape. meld compares two roots and makes the larger a child of the smaller: , and thus insert too. extract-min removes the root and recombines its children in two passes: pair them left to right and combine the results right to left. decrease-key cuts the node’s subtree and melds it with the root. Its analysis is a longstanding open problem. Fredman et al. (1986) proved amortized for extract-min and conjectured amortized for decrease-key; Fredman (1999) showed this impossible (requiring ), and Pettie (2005) gave the upper bound . In experiments pairing heaps behave almost as if and are often the fastest meldable heaps.
import random
# ---------------- montículo binomial: unir dos montículos = sumar en binario ----------------
class NodoB:
__slots__ = ("k", "rango", "hijos")
def __init__(self, k):
self.k, self.rango, self.hijos = k, 0, []
def enlazar(a, b):
"""Dos árboles binomiales del mismo rango r: el de mayor raíz cuelga del otro. Devuelve un árbol de rango r + 1."""
if b.k < a.k:
a, b = b, a
a.hijos.append(b)
a.rango += 1
return a
class Binomial:
def __init__(self):
self.arboles = {} # rango -> árbol; a lo sumo uno por rango, como los bits de n
self.n = 0
def _anadir(self, t): # el «acarreo»: mientras haya otro árbol del mismo rango, enlazar
while t.rango in self.arboles:
t = enlazar(t, self.arboles.pop(t.rango))
self.arboles[t.rango] = t
def insert(self, k):
self._anadir(NodoB(k)); self.n += 1
def meld(self, otro):
for t in list(otro.arboles.values()):
self._anadir(t)
self.n += otro.n
otro.arboles, otro.n = {}, 0
def extract_min(self):
r = min(self.arboles, key=lambda r: self.arboles[r].k)
t = self.arboles.pop(r)
for h in t.hijos: # los hijos de la raíz son B_{r-1}, ..., B_0: ya forman un montículo
self._anadir(h)
self.n -= 1
return t.k
h = Binomial()
for k in random.Random(2).sample(range(1000), 1000):
h.insert(k)
print("1000 elementos = 0b1111101000; rangos presentes:", sorted(h.arboles), "| bits a 1 de 1000:", [i for i in range(10) if 1000 >> i & 1])
a, b = Binomial(), Binomial()
for k in range(0, 700, 2): a.insert(k)
for k in range(1, 300, 2): b.insert(k)
na, nb = a.n, b.n
a.meld(b)
print(f"meld de {na} y {nb} elementos -> {a.n}, rangos {sorted(a.arboles)} (los bits de {a.n})")
assert [a.extract_min() for _ in range(a.n)] == sorted(list(range(0, 700, 2)) + list(range(1, 300, 2)))
# ---------------- montículo de emparejamiento: un único árbol, meld en O(1) ----------------
class NodoP:
__slots__ = ("k", "hijos")
def __init__(self, k):
self.k, self.hijos = k, []
def meld(a, b):
if a is None: return b
if b is None: return a
if b.k < a.k: a, b = b, a
a.hijos.append(b) # la raíz mayor pasa a ser un hijo de la menor
return a
def extract_min(raiz):
"""Devuelve (mínimo, nueva raíz). Dos pasadas: emparejar de izquierda a derecha y combinar de derecha a izquierda."""
hs = raiz.hijos
pares = [meld(hs[i], hs[i + 1]) if i + 1 < len(hs) else hs[i] for i in range(0, len(hs), 2)]
nueva = None
for t in reversed(pares):
nueva = meld(t, nueva)
return raiz.k, nueva
datos = random.Random(5).sample(range(10**6), 5000)
raiz = None
for k in datos:
raiz = meld(raiz, NodoP(k)) # insertar = meld con un nodo: O(1)
salida = []
while raiz is not None:
k, raiz = extract_min(raiz)
salida.append(k)
assert salida == sorted(datos)
print("pairing heap: 5000 inserciones en O(1) y 5000 extract-min, salida ordenada correctamente")The Fibonacci heap
Binomial heaps distribute the work of insert and meld using binary arithmetic. Fredman and Tarjan (1987) went further with laziness: why link now if it may never be needed? A Fibonacci heap is a lazy binomial heap with a cheap decrease-key operation added.
Marks and cascading cuts are the trick. Without them, arbitrary child cuts could leave long skinny trees with high degree and few nodes; maximum degree would no longer be logarithmic and extract-min would lose its bound. The rule “a node can lose one child, but not two” keeps tree shape close to a binomial tree.
Potential
extract-min is expensive (all roots accumulated through lazy insertions must be consolidated), but its cost was paid earlier. To account for it use the potential method: with the number of trees and the number of marked nodes,
Potential accounts for deferred work: one euro for each root that must be linked and two for each mark announcing a future cut.
With a bound on maximum node degree in a heap of elements:
Proof
Decrease-key. With cuts, actual cost is . Each cut adds a root, so increases by . For marks, cascading cuts each remove one mark (cutting unmarks), and at most one new mark is created, at the last parent. Thus and . Amortized cost is .
Extract-min. Let be the minimum root’s degree and the initial number of trees. roots are processed, so actual cost is . At the end there is one tree per degree, at most , and no new marks: . Amortized cost is .
∎Amortized costs are constant except for extract-min, provided maximum degree is . Marks guarantee this.
Proof
Let be the children of in the order linked to it. When was linked, already had as children (all still children now), so its degree was at least , and since links only join roots of equal degree, also had degree at least . Since then could have lost at most one child: losing a second would have cut it from . Thus . Now bound size by recurrence, the lesson exercise, obtaining . Since (by induction, using ), and .
∎With , , so no node has degree greater than , versus for a binomial heap: the degree bound is worse by a factor , the price of laziness. The Fibonacci sequence gives the structure its name.
Why is it rarely used?
With insert and decrease-key at amortized , Dijkstra drops to and the Fibonacci heap is the textbook heap. In practice it rarely wins, for three reasons.
- Constants and memory. Each node stores parent, child, left and right siblings, degree and mark. Consolidation traverses linked lists, with a much higher cache-miss fraction than a contiguous array. An -ary heap is integers in an array.
- There are few
decrease-key. As seen, random graphs have : saving on a rarely called operation helps little. Even in the worst case the advantage over Johnson’s -ary heap is narrow: that costs when , so Fibonacci wins only a factor of order , constant once . - Bounds are amortized. A single operation may cost . That is unacceptable for real-time systems or tail latency; worst-case variants exist (Brodal heaps, 1996; strict Fibonacci heaps of Brodal, Lagogiannis and Tarjan, 2012), but are even more complicated.
Experimental studies (for example, Cherkassky, Goldberg and Radzik, 1996, and Larkin, Sen and Tarjan, 2014) agree that Fibonacci heaps rarely pay off and implicit -ary and pairing heaps often beat them. Their value is theoretical: they establish the bound and offer a leading example of potential analysis on a real data structure.
The table summarizes bounds to help choose among them (amortized where indicated):
| Operation | Binary | -ary | Binomial | Pairing | Fibonacci |
|---|---|---|---|---|---|
find-min | |||||
insert | amort. | ||||
extract-min | amort. | amort. | |||
decrease-key | and amort. | amort. | |||
meld |
(In a binomial heap, search for the minimum among roots or keep a pointer.)
Now a program checks those bounds: a complete Fibonacci heap with potential accounting. It measures each operation’s actual cost in a random workload of operations and verifies amortized cost never exceeds the theorem’s bounds.
import math, random
PHI = (1 + 5 ** 0.5) / 2
class NodoF:
__slots__ = ("k", "padre", "hijos", "marca", "vivo")
def __init__(self, k):
self.k, self.padre, self.hijos, self.marca, self.vivo = k, None, [], False, True
class Fibonacci:
"""Montículo de Fibonacci con contabilidad del coste real y del potencial Φ = t + 2m."""
def __init__(self):
self.raices, self.min, self.n, self.marcados = [], None, 0, 0
self.coste = 0 # coste real de la última operación
@property
def phi(self):
return len(self.raices) + 2 * self.marcados
def insert(self, k):
x = NodoF(k)
self.raices.append(x)
if self.min is None or k < self.min.k:
self.min = x
self.n += 1
self.coste = 1
return x
def _cortar(self, x):
p = x.padre
p.hijos.remove(x)
x.padre = None
if x.marca:
x.marca = False; self.marcados -= 1
self.raices.append(x)
def decrease_key(self, x, k):
assert k <= x.k
x.k = k
self.coste, p = 1, x.padre
if p is not None and x.k < p.k:
self._cortar(x); self.coste += 1
y = p
while y.padre is not None: # cortes en cascada
if not y.marca:
y.marca = True; self.marcados += 1
break
z = y.padre
self._cortar(y); self.coste += 1
y = z
if x.k < self.min.k:
self.min = x
def extract_min(self):
z = self.min
self.raices.remove(z)
for h in z.hijos:
h.padre = None
if h.marca:
h.marca = False; self.marcados -= 1
self.raices.append(h)
self.n -= 1
pendientes, tabla = self.raices, {}
self.coste = 1 + len(pendientes) # coste real: una unidad por raíz tratada
for x in pendientes:
d = len(x.hijos)
while d in tabla:
y = tabla.pop(d)
if y.k < x.k:
x, y = y, x
y.padre = x; x.hijos.append(y) # enlace: la mayor clave cuelga de la menor
if y.marca:
y.marca = False; self.marcados -= 1
d += 1
tabla[d] = x
self.raices = sorted(tabla.values(), key=lambda r: len(r.hijos))
self.min = min(self.raices, key=lambda r: r.k, default=None)
z.vivo = False
return z
def grado_max(h):
pila, g = list(h.raices), 0
while pila:
x = pila.pop()
g = max(g, len(x.hijos)); pila.extend(x.hijos)
return g
rnd = random.Random(11)
h, nodos = Fibonacci(), []
peor = {"insert": 0, "decrease": 0, "extract": -99}
total_real = total_amort = 0
phi0 = h.phi
for paso in range(20000):
r, phi_antes, n_antes = rnd.random(), h.phi, h.n
if r < 0.45 or h.n < 3:
nodos.append(h.insert(rnd.randint(0, 10**6))); tipo = "insert"
elif r < 0.75:
h.extract_min(); tipo = "extract"
else:
x = rnd.choice(nodos)
while not x.vivo:
x = rnd.choice(nodos)
if x.padre is None and x.k <= 0:
continue
h.decrease_key(x, x.k - rnd.randint(1, 5000)); tipo = "decrease"
amort = h.coste + h.phi - phi_antes
total_real += h.coste; total_amort += amort
if tipo == "extract":
D = math.floor(math.log(n_antes, PHI) + 1e-9)
peor[tipo] = max(peor[tipo], amort - (2 * D + 1)) # holgura frente a la cota 2D(n)+1
else:
peor[tipo] = max(peor[tipo], amort)
assert h.phi >= 0
print("insert: coste amortizado máximo", peor["insert"], "(= 1 + 1)")
print("decrease-key: coste amortizado máximo", peor["decrease"], "(cota 5)")
print("extract-min: amortizado menos (2·D(n)+1), máximo", peor["extract"], "(siempre ≤ 0)")
print(f"suma de costes reales = {total_real}; suma de amortizados = {total_amort}; Φ final − Φ inicial = {h.phi - phi0}")
print(f"identidad Σ amortizado = Σ real + ΔΦ: {total_amort == total_real + h.phi - phi0}")
print(f"n = {h.n}: grado máximo observado {grado_max(h)}, cota ⌊log_φ n⌋ = {math.floor(math.log(h.n, PHI))}, log2 n = {math.log2(h.n):.1f}")Identity is the entire potential method: since and , total amortized cost upper-bounds actual cost. The last line shows observed degree against its theoretical bound: marks keep it well below the worst case.
In libraries
In Python, heapq is the standard tool. It is a binary min heap on an ordinary list, with functions rather than a class: heappush, heappop, heappushpop (insert and extract in one operation, cheaper than both), heapreplace (extract then insert), heapify (the earlier linear construction), plus merge, nsmallest and nlargest. heappop uses the bottom-up heapsort variant: move the hole to a leaf and sift the element up. Since Python 3.14 it also includes max versions (heappush_max, heappop_max, heapify_max…); previously keys were negated. It offers no decrease-key and basic functions cannot take a key; use tuple (prioridad, orden, objeto) instead.
import heapq, itertools, queue, random, time
rnd = random.Random(4)
# 1) heapify es O(n); las operaciones básicas del módulo
datos = [rnd.randint(0, 1000) for _ in range(10)]
a = datos[:]
heapq.heapify(a) # en el sitio, en tiempo lineal (la construcción ascendente de la lección)
print("heapify:", a, "| a[0] es el mínimo:", a[0] == min(datos))
heapq.heappush(a, -5)
print("heappushpop(a, 3) devuelve", heapq.heappushpop(a, 3), "| heapreplace(a, 99) devuelve", heapq.heapreplace(a, 99), "(pop y luego push)")
# 2) trampa de decrease-key: modificar en sitio rompe la invariante
a = sorted(datos) # una lista ordenada ya es un montículo
a[5] = -100 # «decrease-key» ingenuo sobre la posición 5
print("tras a[5] = -100, ¿sigue siendo un montículo?", all(a[(i - 1) // 2] <= a[i] for i in range(1, len(a))))
heapq._siftdown(a, 0, 5) # API privada: sube la posición 5 hasta restaurar el orden
print("tras restaurar con _siftdown:", all(a[(i - 1) // 2] <= a[i] for i in range(1, len(a))), "| mínimo =", a[0])
# 3) trampa de las tuplas: con empates en la prioridad Python compara el segundo campo
class Tarea: # sin __lt__: no se pueden comparar
def __init__(self, nombre): self.nombre = nombre
try:
cola = []
heapq.heappush(cola, (1, Tarea("a")))
heapq.heappush(cola, (1, Tarea("b")))
except TypeError as e:
print("TypeError con empate de prioridad:", e)
cuenta, cola = itertools.count(), [] # solución: un contador como desempate (además da orden FIFO entre iguales)
for nombre in "abc":
heapq.heappush(cola, (1, next(cuenta), Tarea(nombre)))
print("con contador de desempate, salen en orden de llegada:", [heapq.heappop(cola)[2].nombre for _ in range(3)])
# 4) merge perezoso y los k menores
flujos = [sorted(rnd.randint(0, 99) for _ in range(5)) for _ in range(4)]
print("heapq.merge:", list(heapq.merge(*flujos)))
class Cuenta: # cuenta comparaciones de un envoltorio
n = 0
def __init__(self, v): self.v = v
def __lt__(self, otro):
Cuenta.n += 1
return self.v < otro.v
N = 20000
xs = [Cuenta(rnd.random()) for _ in range(N)]
Cuenta.n = 0; menores = heapq.nsmallest(10, xs); c_ns = Cuenta.n
Cuenta.n = 0; sorted(xs)[:10]; c_so = Cuenta.n
print(f"10 menores de {N}: nsmallest {c_ns} comparaciones, sorted {c_so} (n log2 n ≈ {round(N * 14.29)})")
# 5) PriorityQueue (segura entre hilos, con candados) frente a heapq a secas
M = 60000
claves = [rnd.random() for _ in range(M)]
t0 = time.perf_counter(); h = []
for k in claves: heapq.heappush(h, k)
for _ in range(M): heapq.heappop(h)
t_heapq = time.perf_counter() - t0
t0 = time.perf_counter(); pq = queue.PriorityQueue()
for k in claves: pq.put(k)
for _ in range(M): pq.get()
t_pq = time.perf_counter() - t0
print(f"{M} put/get: heapq {t_heapq * 1000:.0f} ms, PriorityQueue {t_pq * 1000:.0f} ms ({t_pq / max(t_heapq, 1e-9):.1f}× más lenta)")Four observations. heapq.merge is lazy and uses a heap of size : merging infinite streams or huge files works without loading everything. nsmallest(10, xs) with small maintains a bounded heap and makes on the order of comparisons, not (for large the documentation recommends sorted; the function sorts on its own only when ). queue.PriorityQueue wraps the same heap in a lock and condition for use between threads, paying that cost on every operation: within one thread use heapq. The tuple trap is the most common in real code: when priorities tie, Python compares the second field and fails (or worse, orders based on the objects); an increasing counter as tie-breaker avoids this and preserves arrival order.
Other languages are similar: C++ std::priority_queue and Rust BinaryHeap are binary max heaps without decrease-key, and Java PriorityQueue cannot delete an arbitrary element below . When decrease-key is needed, write an indexed heap or use lazy insertion.
Common mistakes
Exercises
Step 1 of 4. At most how many swaps does sifting down a node at depth make?
Step 1 of 4. What recurrence does satisfy for ?
MonticuloD(d): a -ary min-heap with push(x), pop() and __len__, storing elements in list self.a. Children of are and the parent of is . Tests check heap order after each operation and that pop uses at most comparisons per level (using values that count comparisons), so pop must select the smallest child in comparisons and compare it once with the sinking element. The starter works for and ignores it otherwise.class MonticuloD:
"""Montículo d-ario de mínimo. self.a es la lista que lo almacena."""
def __init__(self, d):
assert d >= 2
self.d = d
self.a = []
def __len__(self):
return len(self.a)
def push(self, x):
a = self.a
a.append(x)
i = len(a) - 1
while i > 0 and a[i] < a[(i - 1) // 2]:
a[i], a[(i - 1) // 2] = a[(i - 1) // 2], a[i]
i = (i - 1) // 2
def pop(self):
a = self.a
minimo = a[0]
a[0] = a[-1]
a.pop()
i = 0
while 2 * i + 1 < len(a):
c = 2 * i + 1
if c + 1 < len(a) and a[c + 1] < a[c]:
c += 1
if a[c] < a[i]:
a[i], a[c] = a[c], a[i]
i = c
else:
break
return minimoSummary
meld and decrease-key with added complexity, often without saving time.- Sorting lower-bounds priority queues: insertions and extractions cost comparisons, so a heap with per operation is optimal and, in the comparison model, Dijkstra (which outputs vertices sorted by distance) cannot beat .
- A binary heap is a complete tree in an array: parent , children and , height . Sift-up (insert, decrease-key) and sift-down (extract-min) restore order through the invariant of one doubtful edge.
- Bottom-up construction makes swaps versus for insertions; heapsort uses it and obtains worst-case with constant memory, but loses to quicksort on cache behavior.
decrease-keyneeds a position index (anddeletesifts up and down) or the lazyheapqalternative; for -ary heaps, the worst-case optimum grows with the proportion ofdecrease-key(Johnson’s rule ), but in practice or almost always wins.- Binomial heaps perform
meldlike binary addition; pairing heaps are fastest in practice and their analysis remains open; Fibonacci achieves amortized fordecrease-keywith potential and marks keeping degree , and rarely justifies its constants.