Module contents
Lesson 6 of 33Core 105 min

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 kk sorted streams. To merge kk sorted files (database compaction or the merge phase of external sorting), inspect the smallest of the kk 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 kk largest items in a stream. A search engine seeking the 1010 best results among millions of candidates cannot keep them all: it maintains the 1010 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 O(1)\bigO(1) and extract-min for O(n)\bigO(n); 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 nn distinct keys: insert all and extract them one by one, producing sorted output. This is a comparison sort costing T(n)T(n). By the sorting lower bound, its decision tree has at least n!n! leaves and therefore depth at least log⁡2(n!)\log_2(n!). The second inequality is n!≥(n/e)nn! \ge (n/e)^n.

∎

This bound has three consequences. A heap with insert and extract-min in O(log⁡n)\bigO(\log n) is optimal up to constants. insert can be O(1)\bigO(1) amortized (as in Fibonacci heaps), but then extract-min must cost Ω(log⁡n)\Omega(\log n) amortized. And Dijkstra, extracting vertices in increasing distance, sorts them by distance: no comparison algorithm delivering that order can beat Ω(nlog⁡n)\Omega(n \log n), making the O(m+nlog⁡n)\bigO(m + n\log n) 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 O(mlog⁡2/3n)\bigO(m \log^{2/3} n), better than O(m+nlog⁡n)\bigO(m + n\log n) 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 nn keys can be sorted in time n S(n)n\,S(n), there is a priority queue with insert and extract-min in O(S(n))\bigO(S(n)): 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 nn 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 A[0]A[0] and an arbitrary value cannot be searched for without scanning everything.

How tall is the tree? If its last level is hh, levels 0,…,h−10, \dots, h-1 are full and contain 2h−12^h - 1 nodes, while level hh has between 11 and 2h2^h. Thus 2h≤n≤2h+1−12^h \le n \le 2^{h+1} - 1, that is:

Operation cost is therefore a multiple of ⌊log⁡2n⌋\lfloor \log_2 n \rfloor: with a million elements, 1919. The first interactive shows the same structure both ways at once; each item moves with its swap in the tree and array.

InteractiveThe heap as tree and array
Complete tree589121619143722413325273044Array (the same structure in contiguous memory)01234567891011121314589121619143722413325273044
  • token just moved
  • compared in this step
  • selected for decrease-key
  • edge violating heap order
  • path from root to last leaf
Min-heap with 15 elements. Select a leaf (click a node or cell), decrease its key and watch it rise step by step. You can also insert or extract the minimum.
6
3
Elements nn15
Height ⌊log⁡2n⌋\lfloor \log_2 n \rfloor3
Path to last leaf3 edges
Comparisons (operation)0
Swaps (operation)0
Heap ordersatisfied
A min-heap with 15 elements, drawn as a complete tree (above) and an array (below). Each item is the same in both views and moves with every swap. Start with leaf 44 selected: press «decrease-key» to lower it to 3 and watch it rise along the parent path, with one comparison and swap per level, to the root; exactly ⌊log₂ 15⌋ = 3 levels. Then extract the minimum: the last element moves to the root and sifts down. Red edges violate order at that instant: the algorithm removes these violations.

Sift up and sift down

Every heap operation locally repairs order. There are only two movements.

  • Sift up (sift-up) position ii: while i>0i > 0 and A[i]<A[padre⁡(i)]A[i] < A[\operatorname{padre}(i)], swap them. Used after insert (the new element enters the first free position, nn) and after decrease-key.
  • Sift down (sift-down) position ii: while ii has a child smaller than A[i]A[i], swap it with its smaller child. Used after extract-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 p=padre⁡(i)p = \operatorname{padre}(i), x=A[i]x = A[i], y=A[p]y = A[p] and suppose x<yx < y. After the swap, A[p]=xA[p] = x and A[i]=yA[i] = y. Four edges change.

  • (p,i)(p, i): x<yx < y, so it holds.
  • (i,c)(i, c) for each child cc of ii: y≤A[c]y \le A[c] by the second hypothesis, so it holds.
  • (p,s)(p, s) with ss the sibling of ii: before, y≤A[s]y \le A[s] (an edge other than that of ii), and now x<y≤A[s]x < y \le A[s].
  • (padre⁡(p),p)(\operatorname{padre}(p), p): the only edge that may fail, entering the new position pp.

The second condition remains for new position pp: its children are now ii (containing yy) and ss. Edge (padre⁡(p),p)(\operatorname{padre}(p), p) held before the swap because p≠ip \ne i, so A[padre⁡(p)]≤yA[\operatorname{padre}(p)] \le y; also y≤A[s]y \le A[s]. Thus A[padre⁡(p)]A[\operatorname{padre}(p)] exceeds neither child of pp. If x≥yx \ge y there is no swap and the only doubtful edge, (p,i)(p, i), holds. If i=0i = 0 there is no incoming edge and the hypothesis says it is already a heap.

∎

Sift-up terminates because ii decreases, after at most ⌊log⁡2n⌋\lfloor \log_2 n \rfloor swaps. When insert puts the new element at position nn, 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 ii to its children and that A[padre⁡(i)]≤A[c]A[\operatorname{padre}(i)] \le A[c] for both children cc; if the smaller child cc satisfies A[c]<A[i]A[c] < A[i], swapping restores the invariant with i:=ci := c. The proof is the lemma’s with roles reversed.

Counting comparisons: insert and decrease-key make at most ⌊log⁡2n⌋\lfloor \log_2 n \rfloor (one per level). extract-min makes at most 2⌊log⁡2(n−1)⌋2\lfloor \log_2 (n-1) \rfloor: per level, compare the two children to find the smaller, then compare that child with the sinking element. With n=106n = 10^6 these are 1919 and 3838. If the array grows, use dynamic-array doubling, adding amortized O(1)\bigO(1) to each insert without changing the above. There is a pleasant surprise for insert: although worst case is ⌊log⁡2n⌋\lfloor \log_2 n \rfloor, randomly ordered keys barely sift up (in the cells below, about 1.31.3 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 nn elements, what does turning it into a heap cost? The obvious option is to insert the nn elements one at a time. In the worst case (decreasing keys, each rising to the root) this costs ∑i⌊log⁡2(i+1)⌋=(n+1)⌊log⁡2(n+1)⌋−2⌊log⁡2(n+1)⌋+1+2=Θ(nlog⁡n)\sum_{i} \lfloor \log_2 (i+1) \rfloor = (n+1)\lfloor\log_2(n+1)\rfloor - 2^{\lfloor \log_2(n+1) \rfloor + 1} + 2 = \Theta(n\log n) 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 ⌊n/2⌋−1\lfloor n/2 \rfloor - 1. Traversing positions from there to 00 and sifting each down makes each subtree a heap with both children already prepared.

Correctness follows from a simple invariant: before sifting down position ii, every position j>ij > i roots a subtree that is already a heap. The children of ii satisfy 2i+1>i2i + 1 > i, so the sift-down lemma’s hypothesis holds within the subtree of ii, which has no parent; after sifting, the subtree of ii is a heap. On reaching i=0i = 0, 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 ii, the longest path to a leaf always descends through the left child (the tree fills from the left), and the index of the descendant jj levels down that path is 2j(i+1)−12^j(i+1) - 1. That descendant exists if and only if 2j(i+1)−1≤n−12^j(i+1) - 1 \le n - 1, that is, i+1≤n/2ji + 1 \le n/2^j. Thus

#{v:h(v)≥j}=⌊n/2j⌋(j≥1).\#\{ v : h(v) \ge j \} = \lfloor n / 2^j \rfloor \quad (j \ge 1).

Summing by layers, ∑vh(v)=∑j≥1#{v:h(v)≥j}=∑j≥1⌊n/2j⌋\sum_v h(v) = \sum_{j \ge 1} \#\{v : h(v) \ge j\} = \sum_{j \ge 1} \lfloor n/2^j \rfloor. This sum is the exponent of 22 in n!n! (Legendre’s formula), equal to n−s2(n)n - s_2(n). 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 vv down costs at most 2h(v)2h(v) comparisons, and the sum over nodes is 2(n−s2(n))<2n2(n - s_2(n)) < 2n.

∎

The idea is a power sum: with nn nodes, half are leaves (work 00), a quarter have height 11 (work ≤1\le 1), an eighth height 22, and so on. Work per height level decreases as height grows, and the sum converges to nn. With insertions, by contrast, the largest level (the bottom) pays the most work: each last-level node can rise hh levels.

InteractiveWhy construction costs O(n)
Swaps while sifting each node down (darker = more work)433222211111111················dot = leaf (16 nodes): nothing to sift down · each cell costs at most its heightTotal work per tree levellevel 0 · 1 node4level 1 · 2 nodes6level 2 · 4 nodes8level 3 · 8 nodes8level 4 · 16 nodes0solid: actual · dashed: level maximum (nodes × height)Swaps per element by n (worst case)012345677153163127255n (logarithmic scale)
  • bottom-up (Floyd)
  • nn insertions
  • 1 swap per element
  • log⁡2n\log_2 n
  • leaf (nothing to sift down)
With n = 31: n log₂ n ≈ 154 and 2n = 62.
31
Method
Input
Swaps, bottom-up26
Swaps, nn insertions98
Bottom-up bound ∑h(v)=n−s2(n)\sum h(v) = n - s_2(n)26 (31 − 5)
Insertion bound ∑depth(v)\sum \text{depth}(v)98
Leaves (no work in Floyd)16 of 31
Comparisons (current method)52
Bottom-up makes 26 swaps, never more than n−s2(n)=26n - s_2(n) = 26, less than n=31n = 31. At least half the nodes (16) are leaves: they do no work.
Each tree cell is a node; its color is the number of swaps it causes under the selected method. With n=31n = 31 in the worst case, bottom-up construction (blue) makes 26 swaps and 31 insertions (orange) make 98. Switch methods and see where color concentrates: at the top, with few nodes and much height, or the bottom, where most nodes are. In the middle is total work per level versus its maximum. Below are swaps per element versus nn: bottom-up stays below 1 and insertions grow like log₂ n. Random inputs lower both, but only bottom-up has a guarantee.

And O(n)\bigO(n) 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 O(n)\bigO(n) and perform nn extractions of O(log⁡n)\bigO(\log n).

Its cost is always Θ(nlog⁡n)\Theta(n \log n), including the worst case; it uses O(1)\bigO(1) 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 nlog⁡nn\log n and constant space. Hybrid sorts (introsort) therefore use heapsort as a safety net when partitioning degrades.

Count comparisons: each extraction sifts down Θ(log⁡n)\Theta(\log n) levels with 2 comparisons per level, so heapsort makes on the order of 2nlog⁡2n2n\log_2 n in the worst case. The lower bound is log⁡2n!≈nlog⁡2n\log_2 n! \approx n\log_2 n: a factor 22 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 nlog⁡2nn\log_2 n, 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 ii to 2i+12i + 1: 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.

[ ]Floyd construction versus insertions, and heapsort comparison countsBrowser
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 n−s2(n)n - s_2(n) exactly (for n=2k−1n = 2^k - 1, with n−kn - k): bottom-up construction on decreasing input attains the theorem’s bound. Random input drops to about 0.74 n0.74\,n swaps. Insertions on decreasing input make Θ(nlog⁡n)\Theta(n\log n) (for n=65 535n = 65\,535, about 1414 times nn), and on random input about 1.3 n1.3\,n: 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 1.71.7 and 1.8 nlog⁡2n1.8\,n\log_2 n comparisons on random input, and the bottom-up variant nearly nlog⁡2nn\log_2 n (33 or 4 %4\,\% more), between 1515 and 21 %21\,\% above the lower bound log⁡2n!\log_2 n!.

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, Θ(n)\Theta(n).

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 [1,10,2,11,12,3,4][1, 10, 2, 11, 12, 3, 4], deleting 1111 (position 3) replaces it with 44 (the last), and 4<104 < 10: 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 xx, insert a new entry (k,x)(k, x) while leaving the old one in the heap. On extraction, if an entry’s key does not match the best known for xx (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 mm entries (one per successful relaxation) instead of nn, but log⁡m≤2log⁡n\log m \le 2\log n, so Dijkstra remains O(mlog⁡n)\bigO(m \log n). With the index, the heap holds at most nn elements and there are ≤m\le m decrease-key at cost O(log⁡n)\bigO(\log n), 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.

[ ]Indexed binary heap from scratchBrowser
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 kk streams costs O(Nlog⁡k)\bigO(N\log k), not O(Nlog⁡N)\bigO(N\log N): each element pays for heap size kk, not data size. Third, top-kk from a stream with a heap of size kk processes almost all elements with one comparison against the minimum: a new element enters the heap rarely (in random order, element ii enters with probability k/ik/i, for about kln⁡(n/k)k\ln(n/k) entries total).

d-ary heaps

Nodes need not have two children. In a dd-ary heap, the children of ii are di+1,…,di+dd i + 1, \dots, d i + d and its parent is ⌊(i−1)/d⌋\lfloor (i-1)/d \rfloor.

The effect on costs is asymmetric. Sifting up is cheaper because there are log⁡dn\log_d n levels, one comparison per level, and log⁡dn=ln⁡n/ln⁡d\log_d n = \ln n / \ln d decreases as dd rises. Sifting down costs more per level: choose the smallest of dd children (d−1d - 1 comparisons), then compare it with the sinking element (one more), so extract-min costs dlog⁡dn=dln⁡dln⁡nd \log_d n = \frac{d}{\ln d} \ln n comparisons. Coefficient d/ln⁡dd/\ln d is minimized at d=ed = e: it is 2.8852.885 for d=2d = 2, 2.7312.731 for d=3d = 3 and 2.8852.885 again for d=4d = 4. 22 and 44 agree because 4/ln⁡4=4/(2ln⁡2)=2/ln⁡24/\ln 4 = 4/(2\ln 2) = 2/\ln 2. Thus, in extract-min comparisons, the 44-ary heap does not lose to binary while its tree is half as tall (for a million elements, 1010 levels versus 1919): decrease-key and insert cost half and the path touches half as many cache lines.

If each element undergoes on average ρ\rho decrease-key (in Dijkstra, ρ≈m/n\rho \approx m/n in the worst case, one per edge), worst-case model cost per element is (d+ρ)log⁡dn(d + \rho)\log_d n, and the best dd grows with ρ\rho.

C(d)=(d+ρ) ln⁡nln⁡dC(d) = (d + \rho)\,\frac{\ln n}{\ln d}
Cost per element: one extract-min at dd comparisons per level and ρ\rho sifts up at one per level, across log⁡dn\log_d n levels.
1/4

Johnson (1975) turned this into a rule: with d=max⁡(2,⌈m/n⌉)d = \max(2, \lceil m/n \rceil), Dijkstra and Prim cost O(mlog⁡2+m/nn)\bigO(m \log_{2 + m/n} n). For m=n1+εm = n^{1+\varepsilon} with constant ε\varepsilon, this is O(m/ε)\bigO(m/\varepsilon): linear in edges using only an array and no Fibonacci heap. For m=Θ(n2)m = \Theta(n^2) it matches the linear-array algorithm, O(n2)\bigO(n^2).

InteractiveWhich arity is best?
Worst-case comparisons per vertex, by arity025507510023J4★5678910111213141516heap arity d (★ best in model · J Johnson’s rule)
  • insertion
  • extract-min (dd per level)
  • decrease-key (ρ\rho upward traversals)
  • continuous model (d+1+ρ)ln⁡n/ln⁡d(d+1+\rho)\ln n/\ln d
Scenario
1.00 M
3
4
Best arity in model4
Johnson's rule max⁡(2,⌈m/n⌉)\max(2,\lceil m/n \rceil)3
Height with d=2d = 2 / chosen dd19 / 10
Cost per vertex, d=2d = 2114
Cost per vertex, chosen dd80
Best saving over binary1.43×
With nn = 1.00 M and ρ=3\rho = 3, the binary heap has height 19 and the heap with arity 4 has height 10. Extract-min costs 4·10 = 40 comparisons and the 3 decrease-key operations cost 30.
Worst-case comparisons per vertex versus heap arity dd, with one insertion, one extract-min and ρ\rho decrease-key operations per vertex (stacked bars), and exact dd-ary heap height. With n=106n = 10^6: without decrease-key (events), d=4d = 4 is best, at 50 comparisons versus binary's 57; in a sparse graph (ρ=3\rho = 3), d=4d = 4 also wins (tied with d=6d = 6), 80 versus 114; in a dense graph (ρ=12\rho = 12), it rises to d=10d = 10, 138 versus 285. Increase ρ\rho and watch the orange portion grow and the optimum shift right; J marks Johnson's rule.

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 O(nlog⁡(m/n))\bigO(n \log(m/n)) (Noshita, 1985), much less than mm, and each usually rises only a few levels. The next cell measures this with an indexed dd-ary heap and lazy heapq.

[ ]d-ary heaps and heapq in practiceBrowser
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 nn or mm, not mm; total comparisons are nearly equal for d=2,3,4d = 2, 3, 4 (minimum near d=3d = 3) and clearly rise for d=8d = 8 and 1616, because cost is then dominated by extract-min of dlog⁡dnd \log_d n. What always decreases with dd is moves (lower height), which cost cache accesses on a real machine. This is why tuned implementations often prefer d=4d = 4 to d=2d = 2 (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 nn and n′n' costs Θ(n+n′)\Theta(n + n'): 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 kk, BkB_k, is defined recursively: B0B_0 is a node and BkB_k is obtained by linking two Bk−1B_{k-1}, making one root a child of the other. By induction, BkB_k has 2k2^k nodes, its root has degree kk and its children root Bk−1,…,B1,B0B_{k-1}, \dots, B_1, B_0 (hence the name: at depth ii there are (ki)\binom{k}{i} nodes). To link while maintaining heap order, attach the root with the larger key: one link costs O(1)\bigO(1).

A binomial heap with nn elements is a list of heap-ordered binomial trees, at most one of each rank, with rank kk present if and only if bit kk of nn equals 11. There is a unique heap shape for each nn, with at most ⌊log⁡2n⌋+1\lfloor \log_2 n \rfloor + 1 trees.

  • meld is binary addition: traverse ranks from low to high and link two trees of the same rank whenever encountered, carrying a higher-rank tree. Cost O(log⁡n)\bigO(\log n).
  • insert is meld with a one-node heap: incrementing a binary counter, so nn consecutive insertions cost O(n)\bigO(n) total (amortized O(1)\bigO(1)), by the counter’s amortized analysis.
  • extract-min finds the smallest among O(log⁡n)\bigO(\log n) roots, removes it and performs meld on its children (exactly Bk−1,…,B0B_{k-1}, \dots, B_0, already a binomial heap): O(log⁡n)\bigO(\log n).
  • decrease-key sifts up in its tree, whose height is ≤log⁡2n\le \log_2 n: O(log⁡n)\bigO(\log n).

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: O(1)\bigO(1), 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 O(log⁡n)\bigO(\log n) for extract-min and conjectured amortized O(1)\bigO(1) for decrease-key; Fredman (1999) showed this impossible (requiring Ω(log⁡log⁡n)\Omega(\log\log n)), and Pettie (2005) gave the upper bound O(22log⁡log⁡n)\bigO(2^{2\sqrt{\log\log n}}). In experiments pairing heaps behave almost as if O(1)\bigO(1) and are often the fastest meldable heaps.

[ ]Binomial and pairing heaps: meld in practiceBrowser
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 t+2mt + 2m

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 t(H)t(H) the number of trees and m(H)m(H) the number of marked nodes,

Φ(H)=t(H)+2 m(H).\Phi(H) = t(H) + 2\,m(H).

Potential accounts for deferred work: one euro for each root that must be linked and two for each mark announcing a future cut.

With D(n)D(n) a bound on maximum node degree in a heap of nn elements:

Proof

Decrease-key. With cc cuts, actual cost is 1+c1 + c. Each cut adds a root, so tt increases by cc. For marks, c−1c - 1 cascading cuts each remove one mark (cutting unmarks), and at most one new mark is created, at the last parent. Thus Δm≤−(c−1)+1=2−c\Delta m \le -(c-1) + 1 = 2 - c and ΔΦ≤c+2(2−c)=4−c\Delta\Phi \le c + 2(2 - c) = 4 - c. Amortized cost is (1+c)+ΔΦ≤5(1 + c) + \Delta\Phi \le 5.

Extract-min. Let k≤D(n)k \le D(n) be the minimum root’s degree and tt the initial number of trees. r=t−1+kr = t - 1 + k roots are processed, so actual cost is 1+r1 + r. At the end there is one tree per degree, at most D(n)+1D(n) + 1, and no new marks: ΔΦ≤D(n)+1−t\Delta\Phi \le D(n) + 1 - t. Amortized cost is ≤1+(t−1+k)+(D(n)+1−t)=k+D(n)+1≤2D(n)+1\le 1 + (t - 1 + k) + (D(n) + 1 - t) = k + D(n) + 1 \le 2D(n) + 1.

∎

Amortized costs are constant except for extract-min, provided maximum degree is O(log⁡n)\bigO(\log n). Marks guarantee this.

Proof

Let y1,…,yky_1, \dots, y_k be the children of xx in the order linked to it. When yiy_i was linked, xx already had y1,…,yi−1y_1, \dots, y_{i-1} as children (all still children now), so its degree was at least i−1i - 1, and since links only join roots of equal degree, yiy_i also had degree at least i−1i - 1. Since then yiy_i could have lost at most one child: losing a second would have cut it from xx. Thus grado⁡(yi)≥i−2\operatorname{grado}(y_i) \ge i - 2. Now bound size by recurrence, the lesson exercise, obtaining Fk+2F_{k+2}. Since Fk+2≥φkF_{k+2} \ge \varphi^k (by induction, using φ2=φ+1\varphi^2 = \varphi + 1), n≥φkn \ge \varphi^k and k≤log⁡φnk \le \log_\varphi n.

∎

With n=106n = 10^6, log⁡φn≈28.7\log_\varphi n \approx 28.7, so no node has degree greater than 2828, versus log⁡2n≈19.9\log_2 n \approx 19.9 for a binomial heap: the degree bound is worse by a factor log⁡φ2≈1.44\log_\varphi 2 \approx 1.44, the price of laziness. The Fibonacci sequence gives the structure its name.

InteractiveCascading cuts and potential
Root list (dashed line) and trees73121595142min · g3118164g2136g110g0
  • marked node (lost a child)
  • minimum
  • selected
  • involved in this step
  • root list (gk above each root = its degree k)
Binomial forest: 4 trees (degrees 0, 1, 2 and 3) and no marked nodes. Try “Suggest node” and decrease keys two or three times: the first cut marks the parent; the second cuts it too.
1
Trees tt4
Marked nodes mm0
Potential Φ=t+2m\Phi = t + 2m4
Cuts if decreased below parent-
Last operation: actual cost…
Potential change ΔΦ\Delta\Phi…
Amortized cost…
Degree bound ⌊log⁡φn⌋\lfloor \log_\varphi n \rfloor5 (n = 15)
A 15-node Fibonacci heap in four binomial trees, unmarked, with Φ = 4. Click a node and decrease its key below its parent's: it is cut and becomes a root, and its parent is marked (solid fill in the text color). To see a cascade, press «Sugerir nodo» and «decrease-key» six times; the first three cost 2 and raise Φ by 3 (amortized 5), and the fifth cuts two nodes in a cascade (actual cost 3, Φ unchanged). Then «Extraer mínimo»: actual cost is 11, but Φ falls by 10 and amortized cost is 1. Savings from cheap operations pay for consolidation.

Why is it rarely used?

With insert and decrease-key at amortized O(1)\bigO(1), Dijkstra drops to O(m+nlog⁡n)\bigO(m + n\log n) and the Fibonacci heap is the textbook heap. In practice it rarely wins, for three reasons.

  1. 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 44-ary heap is integers in an array.
  2. There are few decrease-key. As seen, random graphs have O(nlog⁡(m/n))\bigO(n \log(m/n)): saving on a rarely called operation helps little. Even in the worst case the advantage over Johnson’s dd-ary heap is narrow: that costs O(mlog⁡n/log⁡(m/n))\bigO(m \log n / \log(m/n)) when m≥2nm \ge 2n, so Fibonacci wins only a factor of order log⁡n/log⁡(m/n)\log n / \log(m/n), constant once m=n1+εm = n^{1+\varepsilon}.
  3. Bounds are amortized. A single operation may cost Θ(n)\Theta(n). 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 dd-ary and pairing heaps often beat them. Their value is theoretical: they establish the O(m+nlog⁡n)\bigO(m + n\log n) 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):

OperationBinarydd-aryBinomialPairingFibonacci
find-minO(1)\bigO(1)O(1)\bigO(1)O(log⁡n)\bigO(\log n)O(1)\bigO(1)O(1)\bigO(1)
insertO(log⁡n)\bigO(\log n)O(log⁡dn)\bigO(\log_d n)O(1)\bigO(1) amort.O(1)\bigO(1)O(1)\bigO(1)
extract-minO(log⁡n)\bigO(\log n)O(dlog⁡dn)\bigO(d\log_d n)O(log⁡n)\bigO(\log n)O(log⁡n)\bigO(\log n) amort.O(log⁡n)\bigO(\log n) amort.
decrease-keyO(log⁡n)\bigO(\log n)O(log⁡dn)\bigO(\log_d n)O(log⁡n)\bigO(\log n)Ω(log⁡log⁡n)\Omega(\log\log n) and O(22log⁡log⁡n)\bigO(2^{2\sqrt{\log\log n}}) amort.O(1)\bigO(1) amort.
meldΘ(n)\Theta(n)Θ(n)\Theta(n)O(log⁡n)\bigO(\log n)O(1)\bigO(1)O(1)\bigO(1)

(In a binomial heap, search for the minimum among O(log⁡n)\bigO(\log n) 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 20 00020\,000 operations and verifies amortized cost never exceeds the theorem’s bounds.

[ ]Measured Fibonacci heap and potentialBrowser
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 ∑amortizado=∑real+Φfinal−Φinicial\sum \text{amortizado} = \sum \text{real} + \Phi_{\text{final}} - \Phi_{\text{inicial}} is the entire potential method: since Φ≥0\Phi \ge 0 and Φinicial=0\Phi_{\text{inicial}} = 0, 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.

[ ]heapq: construction, merge, k smallest and pitfallsBrowser
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 kk: merging infinite streams or huge files works without loading everything. nsmallest(10, xs) with small kk maintains a bounded heap and makes on the order of nn comparisons, not nlog⁡nn \log n (for large kk the documentation recommends sorted; the function sorts on its own only when k≥nk \ge n). 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 O(n)\bigO(n). When decrease-key is needed, write an indexed heap or use lazy insertion.

Common mistakes

Exercises

NumericComparisons in extract-min
A binary min-heap has n=106n = 10^6 elements. When extracting the minimum, what is the maximum number of key comparisons made by the standard algorithm (one between the children and one with the sinking element per level)?
NumericMinimum subtree size for degree 10
In a Fibonacci heap, what is the fewest nodes in the subtree of a node of degree 1010 (including the node itself)?
NumericWorst-case bottom-up construction
What is the maximum number of swaps in Floyd's bottom-up construction on n=1023n = 1023 elements? This is ∑vh(v)\sum_v h(v), the sum of all node heights.
NumericComparisons in a 4-ary heap
A 44-ary min-heap has n=106n = 10^6 elements. What is the maximum number of key comparisons in extract-min (33 per level to find the smallest of 44 children and one with the sinking element)?
QuizChoosing the right structure
Three workloads: (A) Dijkstra on a dense graph with n=103n = 10^3 and m≈4⋅105m \approx 4 \cdot 10^5; (B) Dijkstra on a sparse graph with m≈3nm \approx 3n and n=107n = 10^7; (C) an event simulator with millions of insertions and extractions and very few cancellations. Which choice is most sensible?
QuizDeleting an arbitrary element
In an indexed heap, delete position ii by placing the last array element in its hole. What must happen next to restore order?
QuizWhen do Fibonacci heaps pay off?
Why is a Fibonacci heap rarely the best choice in practice despite its asymptotic bound?
ProofBottom-up construction makes at most 2n swaps
Prove: In a heap of nn nodes with height h=⌊log⁡2n⌋h = \lfloor \log_2 n \rfloor, Floyd's bottom-up construction makes at most 2n2n swaps (and hence fewer than 4n4n comparisons).
0
Count by depth: a node at depth dd can sift down at most to the last level, hh.

Step 1 of 4. At most how many swaps does sifting down a node at depth dd make?

ProofA degree-k node has at least F_(k+2) nodes
Prove: In a Fibonacci heap, every degree-kk node xx has a subtree of at least Fk+2F_{k+2} nodes. Deduce that the maximum degree with nn nodes is O(log⁡n)\bigO(\log n).
0
Let sks_k be the minimum possible subtree size of a degree-kk node. For children y1,…,yky_1, \dots, y_k of xx in link order, we know (when yiy_i was linked, xx had degree at least i−1i - 1; since then yiy_i has lost at most one child) that grado⁡(yi)≥i−2\operatorname{grado}(y_i) \ge i - 2 for i≥2i \ge 2.

Step 1 of 4. What recurrence does sks_k satisfy for k≥2k \ge 2?

CodeA generic d-ary heap
Implement class MonticuloD(d): a dd-ary min-heap with push(x), pop() and __len__, storing elements in list self.a. Children of ii are di+1,…,di+dd i + 1, \dots, d i + d and the parent of ii is (i−1)//d(i - 1)//d. Tests check heap order after each operation and that pop uses at most dd comparisons per level (using values that count comparisons), so pop must select the smallest child in d−1d - 1 comparisons and compare it once with the sinking element. The starter works for d=2d = 2 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 minimo
Shift+Enter to run

Summary

Key idea
A priority queue powers “always the next most urgent”: a binary heap implements it in an array with O(log⁡n)\bigO(\log n) per operation, builds in O(n)\bigO(n) by sifting bottom-up (half the nodes are leaves), and variants (arity dd, binomial, pairing, Fibonacci) buy cheap meld and decrease-key with added complexity, often without saving time.
  • Sorting lower-bounds priority queues: nn insertions and nn extractions cost Ω(nlog⁡n)\Omega(n\log n) comparisons, so a heap with O(log⁡n)\bigO(\log n) per operation is optimal and, in the comparison model, Dijkstra (which outputs vertices sorted by distance) cannot beat Ω(nlog⁡n)\Omega(n\log n).
  • A binary heap is a complete tree in an array: parent ⌊(i−1)/2⌋\lfloor (i-1)/2 \rfloor, children 2i+12i+1 and 2i+22i+2, height ⌊log⁡2n⌋\lfloor \log_2 n \rfloor. Sift-up (insert, decrease-key) and sift-down (extract-min) restore order through the invariant of one doubtful edge.
  • Bottom-up construction makes ∑vh(v)=n−s2(n)<n\sum_v h(v) = n - s_2(n) < n swaps versus Θ(nlog⁡n)\Theta(n\log n) for nn insertions; heapsort uses it and obtains worst-case nlog⁡nn\log n with constant memory, but loses to quicksort on cache behavior.
  • decrease-key needs a position index (and delete sifts up and down) or the lazy heapq alternative; for dd-ary heaps, the worst-case optimum grows with the proportion of decrease-key (Johnson’s rule d=⌈m/n⌉d = \lceil m/n \rceil), but in practice d=3d = 3 or 44 almost always wins.
  • Binomial heaps perform meld like binary addition; pairing heaps are fastest in practice and their analysis remains open; Fibonacci achieves amortized O(1)\bigO(1) for decrease-key with potential t+2mt + 2m and marks keeping degree log⁡φn\log_\varphi n, and rarely justifies its constants.