Simple Algorithm
Algorithms & Data Structures · Optimal · 28 min

External-Memory & Cache-Oblivious Algorithms

The I/O model, B-trees, and algorithms that are fast on every level of cache.

With 8 GiB of memory and 1 MiB disk blocks, a terabyte of 8-byte keys sorts in just two passes over the disk, and no comparison-based algorithm can do fundamentally better. Aggarwal and Vitter (1988) explained why with three numbers: the data size NN, the memory size MM and the block size BB. A decade later, Frigo, Leiserson, Prokop and Ramachandran showed that many algorithms reach the optimal number of block transfers without knowing MM or BB at all, which makes them optimal at every level of a memory hierarchy at once.

What you’ll learn

  • State the external-memory model and its four fundamental bounds: scanning, sorting, permuting and searching.
  • Derive the multiway merge sort bound O((N/B)log⁡M/B(N/B))O((N/B)\log_{M/B}(N/B)), and sketch Aggarwal and Vitter's counting lower bound.
  • Prove the log⁡B+1(N+1)\log_{B+1}(N+1) search lower bound, and show that the van Emde Boas layout achieves O(log⁡BN)O(\log_B N) transfers without knowing BB.
  • Analyze cache-oblivious matrix transposition and multiplication under the tall-cache assumption.
  • State what obliviousness cannot do: the lg⁡e\lg e factor for searching, and the tall cache that optimal sorting requires.

The external-memory model

ProblemI/OsIn internal memory
scan NN itemsscan⁡(N)=Θ(N/B)\operatorname{scan}(N) = \Theta(N/B)Θ(N)\Theta(N)
sort NN itemssort⁡(N)=Θ(NBlog⁡M/BNB)\operatorname{sort}(N) = \Theta\big(\tfrac{N}{B}\log_{M/B}\tfrac{N}{B}\big)Θ(Nlog⁡N)\Theta(N \log N)
permute NN itemsΘ(min⁡(N,sort⁡(N)))\Theta\big(\min(N, \operatorname{sort}(N))\big)Θ(N)\Theta(N)
search among NN sorted itemsΘ(log⁡BN)\Theta(\log_B N)Θ(log⁡N)\Theta(\log N)
The sorting and permuting bounds are for comparison-based algorithms that move items without encoding them (the indivisibility assumption); the searching bound is for comparison-based structures.

Two surprises hide in this table. First, log⁡M/B\log_{M/B} has an enormous base. With 1 MiB blocks and 8 GiB of memory, M/B=8192M/B = 8192, and a terabyte (2402^{40} bytes) is N/B=220N/B = 2^{20} blocks, so log⁡M/B(N/B)≈1.5\log_{M/B}(N/B) \approx 1.5. Sorting it takes two passes over the data: one to form sorted runs, one to merge all 128 of them at once.

Second, permuting is as hard as sorting. Moving each item straight to its destination costs up to one I/O per item, NN in all, whereas sort⁡(N)\operatorname{sort}(N) is usually far smaller, because one I/O moves BB items. The best way to apply a known permutation is therefore, typically, to sort the items by their destinations.

Predict before you look

A file occupies N/B=228N/B = 2^{28} blocks and memory holds M/B=210M/B = 2^{10} blocks. Multiway merge sort forms sorted runs of MM items, then merges about M/BM/B runs at a time. How many passes over the data does it make, run formation included?

Show the answer

3

Run formation is one pass and leaves N/M=218N/M = 2^{18} runs. Each merge pass divides the number of runs by about 2102^{10}: 218→28→12^{18} \to 2^{8} \to 1, two merge passes. In total 1+2=31 + 2 = 3 passes, matching ⌈log⁡M/B(N/B)⌉=⌈2.8⌉=3\lceil \log_{M/B}(N/B) \rceil = \lceil 2.8 \rceil = 3. Each pass reads and writes every block, so the sort costs about 6⋅2286 \cdot 2^{28} I/Os.

Sorting: multiway merging and its lower bound

DerivationMultiway merge sort: O((N/B) log_{M/B}(N/B)) I/Os
  1. #runs=NM,cost=2NB\#\text{runs} = \frac{N}{M}, \qquad \text{cost} = \frac{2N}{B}

    Runs. Read MM items, sort them in memory, write them back; repeat. One pass of 2N/B2N/B I/Os leaves N/MN/M sorted runs.

  2. #merge passes  =  ⌈log⁡kNM⌉\#\text{merge passes} \;=\; \Big\lceil \log_{k} \frac{N}{M} \Big\rceil

    Merges. Keep one block of each of k=M/B−1k = M/B - 1 runs in memory, plus one output block. Repeatedly move the smallest item to the output, writing the output block when it is full and reading a run's next block when its current one is used up. One pass merges every group of kk runs and costs 2N/B2N/B I/Os:

  3. 2NB(1+⌈log⁡M/B−1NM⌉)  =  O(NB log⁡M/BNB)\frac{2N}{B}\Big(1 + \Big\lceil \log_{M/B - 1}\frac{N}{M} \Big\rceil\Big) \;=\; O\Big(\frac{N}{B}\,\log_{M/B}\frac{N}{B}\Big)

    Total. Since log⁡M/B(M/B)=1\log_{M/B}(M/B) = 1, the run pass and the merge passes combine into one logarithm; replacing k=M/B−1k = M/B - 1 by M/BM/B changes only the constant, because M≥2BM \ge 2B:

DerivationProof sketch: counting orderings
  1. #outcomes of one input  ≤  (MB)⋅{B!first input of an input block1otherwise\#\text{outcomes of one input} \;\le\; \binom{M}{B}\cdot\begin{cases} B! & \text{first input of an input block}\\ 1 & \text{otherwise}\end{cases}

    Track how many of the N!N! input orders are still consistent with what the algorithm knows. Comparisons are free, so when a block enters memory the algorithm learns how its BB items compare with the M−BM - B items already there. That splits the remaining orders into at most (MB)\binom{M}{B} classes, the possible positions of the new items among the old ones, times B!B! for the order within the block if this is its first visit (blocks written by the algorithm were in memory together, so their internal order is already known):

  2. (B!)N/B(MB)t  ≥  N!(B!)^{N/B}\binom{M}{B}^{t} \;\ge\; N!

    There are only N/BN/B first inputs. After tt inputs the algorithm must have narrowed the possibilities down to one order, so

  3. t  ≥  Nlog⁡N−Nlog⁡B−O(N)Blog⁡(eM/B)  =  Ω(NB log⁡M/BNB)t \;\ge\; \frac{N\log N - N\log B - O(N)}{B\log(eM/B)} \;=\; \Omega\Big(\frac{N}{B}\,\log_{M/B}\frac{N}{B}\Big)

    Take logarithms, with log⁡N!=Nlog⁡N−O(N)\log N! = N\log N - O(N), log⁡B!≤Blog⁡B\log B! \le B\log B and log⁡(MB)≤Blog⁡(eM/B)\log\binom{M}{B} \le B\log(eM/B):

The Optimal lesson External Sorting turns this into practice, including replacement selection, which produces runs of expected length 2M2M on random input. The same counting argument gives the permuting bound Ω(min⁡(N,sort⁡(N)))\Omega(\min(N, \operatorname{sort}(N))).

Searching without knowing B

A B-tree with Θ(B)\Theta(B) keys per node matches this bound: O(log⁡BN)O(\log_B N) I/Os per search, insertion and deletion (see the Optimal lesson B-Trees & B+ Trees). With N=109N = 10^9 keys and 255 keys per block, the bound demands at least 4 I/Os, against about 22 for binary search on a sorted array, which misses on all but its last log⁡2B\log_2 B probes.

But a B-tree must know BB. Can one layout of a plain binary search tree be good for every block size at once? Prokop (1999) found one, named after van Emde Boas's recursive priority queue. To lay out a complete binary tree of height hh, cut it at half its height into a top tree and about N\sqrt N bottom trees, each of height about h/2h/2. Store the top tree first and then the bottom trees one after another, each laid out recursively in the same way.

DerivationThe van Emde Boas layout: at most 4 log_B N + 2 transfers per search
  1. 12log⁡2B  ≲  height of a base tree  ≤  log⁡2(B+1)\tfrac12 \log_2 B \;\lesssim\; \text{height of a base tree} \;\le\; \log_2 (B+1)

    Follow the recursion down to the first level at which the pieces have at most BB nodes. Their parents had more than BB nodes and each cut halves the height, so each of these base trees has height at least about 12log⁡2B\tfrac12\log_2 B. A base tree is stored contiguously in at most BB words, so it spans at most 2 blocks, whatever the alignment:

  2. #base trees on the path  ≤  log⁡2N12log⁡2B+1  =  2log⁡BN+1\#\text{base trees on the path} \;\le\; \frac{\log_2 N}{\tfrac12 \log_2 B} + 1 \;=\; 2\log_B N + 1

    A root-to-leaf path of length about log⁡2N\log_2 N passes through base trees one after another, spending at least 12log⁡2B\tfrac12\log_2 B levels in each, so it visits at most about 2log⁡BN+12\log_B N + 1 of them:

  3. Qsearch(N;B)  ≤  4log⁡BN+2  =  O(log⁡BN)Q_{\text{search}}(N; B) \;\le\; 4\log_B N + 2 \;=\; O(\log_B N)

    Two blocks per base tree give the bound. Nothing in the layout depends on BB: only the analysis picks a level of the recursion, and a different BB simply picks a different level.

Layout of a tree with 65,535 keysBlocks of 16 nodesBlocks of 256 nodes
sorted array (binary search)139
breadth-first order, as in a binary heap1410
van Emde Boas order84
the bound 4log⁡BN+24\log_B N + 21810
The most blocks any search touches, computed over every root-to-leaf path and several alignments of the first block. The van Emde Boas layout adapts to both block sizes without being told either.

Cache-oblivious algorithms

The recipe is divide and conquer. Recursion halves a problem until, at some level, a subproblem fits in the cache; the analysis charges the misses at that level, which the algorithm itself never needs to know. Matrix transposition is the classic first example:

python
def transpose(A, T, r0, r1, c0, c1):
    """Set T[c][r] = A[r][c] for r in [r0, r1) and c in [c0, c1), without knowing M or B."""
    if (r1 - r0) * (c1 - c0) <= 16:            # small base case
        for r in range(r0, r1):
            for c in range(c0, c1):
                T[c][r] = A[r][c]
    elif r1 - r0 >= c1 - c0:                    # split the longer side in half
        rm = (r0 + r1) // 2
        transpose(A, T, r0, rm, c0, c1)
        transpose(A, T, rm, r1, c0, c1)
    else:
        cm = (c0 + c1) // 2
        transpose(A, T, r0, r1, c0, cm)
        transpose(A, T, r0, r1, cm, c1)

Splitting the longer side keeps the pieces nearly square. With a tall cache, the recursion reaches pieces whose sides lie between about B/2B/2 and BB and which fit in the cache together with their transposes; each costs O(B)O(B) misses for Θ(B2)\Theta(B^2) elements, so an m×nm \times n transpose costs O(1+mn/B)O(1 + mn/B) misses, as much as a scan. The plain double loop costs Θ(mn)\Theta(mn) misses on large matrices, because one of the two matrices is always walked by columns.

DerivationRecursive matrix multiplication: Θ(n³/(B√M)) misses, obliviously
  1. Q(n)  =  8 Q(n/2)+O(1)Q(n) \;=\; 8\,Q(n/2) + O(1)

    Split each n×nn \times n matrix into four n/2×n/2n/2 \times n/2 blocks and compute the eight block products recursively. The overhead per call is O(1)O(1) misses, so above the cache-sized level the recurrence is

  2. Q(n0)  =  O(n02/B)Q(n_0) \;=\; O\big(n_0^2 / B\big)

    Let n0n_0 be the size at which three blocks fit in the cache, 3n02≤M3n_0^2 \le M, so n0=Θ(M)n_0 = \Theta(\sqrt M). A subproblem of that size is loaded once, at O(n02/B)O(n_0^2/B) misses (the tall cache makes n0≥Bn_0 \ge B, so each block row spans whole lines), and then runs without further misses:

  3. Q(n)  =  (nn0)3O(n02B)  =  O(n3B n0)  =  O(n3BM)Q(n) \;=\; \Big(\frac{n}{n_0}\Big)^{3} O\Big(\frac{n_0^2}{B}\Big) \;=\; O\Big(\frac{n^3}{B\, n_0}\Big) \;=\; O\Big(\frac{n^3}{B\sqrt M}\Big)

    The recursion tree has (n/n0)3(n/n_0)^3 leaves of that size, and they dominate the cost:

That matches tiling and the Hong–Kung lower bound, with no tile size to tune. Sorting has an oblivious optimum too: funnelsort (Frigo et al., 1999), which merges through a recursive tree of buffered mergers called funnels, sorts with O(sort⁡(N))O(\operatorname{sort}(N)) misses under a tall cache.

Check your understanding

Why is a cache-oblivious algorithm that is optimal for every MM and BB in the two-level model also optimal on a machine with L1, L2 and L3 caches and DRAM?

  1. Because a cache-oblivious algorithm never uses memory beyond the L1 cache
  2. Because each adjacent pair of levels acts as a two-level cache with its own MM and BB, and the analysis held for all of them at once
  3. Because a cache-oblivious algorithm measures MM and BB when it starts
  4. Because recursive algorithms never miss in multilevel caches
Show the answer

B. Because each adjacent pair of levels acts as a two-level cache with its own MM and BB, and the analysis held for all of them at once

The algorithm never consults MM or BB, so one and the same execution can be analyzed with L1's parameters, with L2's, and so on, and it is optimal for each pair simultaneously, assuming inclusive levels and LRU-like replacement, up to the constant factors the regularity argument allows.

Limits, dynamic structures and the frontier

Dynamic structures. Bender, Demaine and Farach-Colton (2000; journal version 2005) built a cache-oblivious B-tree that searches in O(log⁡BN)O(\log_B N) transfers and updates in O(log⁡BN+(log⁡2N)/B)O(\log_B N + (\log^2 N)/B) amortized. It keeps the items in a packed-memory array, an array with evenly spread gaps that re-spreads a region whenever it becomes too dense, indexed by a tree in van Emde Boas layout.

Insertions can be much cheaper than searches. A B-tree pays Θ(log⁡BN)\Theta(\log_B N) I/Os per insertion. Buffering insertions and pushing them down in batches, as in the buffer tree (Arge, 2003), the BεB^\varepsilon-tree and the log-structured merge tree (O'Neil, Cheng, Gawlick & O'Neil, 1996) behind LevelDB and RocksDB, brings an insertion down to O(1εB1−εlog⁡BN)O\big(\tfrac{1}{\varepsilon B^{1-\varepsilon}}\log_B N\big) amortized I/Os while a search costs O(1εlog⁡BN)O\big(\tfrac{1}{\varepsilon}\log_B N\big), for any 0<ε≤10 < \varepsilon \le 1. Brodal and Fagerberg (2003) proved this trade-off between insertions and searches optimal.

Key takeaways

  • The external-memory model counts block transfers: scanning costs Θ(N/B)\Theta(N/B), sorting Θ((N/B)log⁡M/B(N/B))\Theta((N/B)\log_{M/B}(N/B)), permuting Θ(min⁡(N,sort⁡(N)))\Theta(\min(N, \operatorname{sort}(N))) and searching Θ(log⁡BN)\Theta(\log_B N); the huge base M/BM/B makes external sorting a matter of a few passes.
  • Multiway merge sort matches the sorting bound, and a count of the N!N! input orders proves it optimal for comparison-based algorithms that move items without encoding them.
  • Cache-oblivious algorithms use neither MM nor BB yet are optimal for all of them, hence at every level of a hierarchy: recursive transposition and multiplication, funnelsort, and the van Emde Boas layout with at most 4log⁡BN+24\log_B N + 2 transfers per search.
  • Obliviousness has proven limits: a factor lg⁡e\lg e for searching, a tall cache for sorting, and no optimal permuting for all MM and BB.

Check yourself

In the interactive lesson these are scored with your confidence, and what you miss comes back for review.

Question 1

In the external-memory model with large blocks, what is asymptotically the cheapest way to apply a known permutation to NN items on disk?

  1. Move each item directly to its destination: NN I/Os, the minimum possible
  2. Load all the items into memory first
  3. Scan once: Θ(N/B)\Theta(N/B) I/Os suffice for any permutation
  4. Sort the items by destination, which costs sort⁡(N)\operatorname{sort}(N), usually far below NN I/Os
Show the answer

D. Sort the items by destination, which costs sort⁡(N)\operatorname{sort}(N), usually far below NN I/Os

Aggarwal and Vitter proved that permuting costs Θ(min⁡(N,sort⁡(N)))\Theta(\min(N, \operatorname{sort}(N))) I/Os. For realistic MM and BB, sort⁡(N)\operatorname{sort}(N) is a small multiple of N/BN/B, far below NN, so sorting by destination wins.

Question 2

Why can no comparison-based structure search NN sorted items in fewer than about log⁡B+1N\log_{B+1} N I/Os?

  1. Each I/O brings at most BB new items into memory, and comparing the query with them leaves at most B+1B + 1 possible intervals, so each I/O divides the N+1N + 1 outcomes by at most B+1B + 1
  2. Because a B-tree has height log⁡BN\log_B N, and B-trees are the only external search structures
  3. Because the search must read every block of the file
  4. Because binary search needs log⁡2N\log_2 N probes and each probe is an I/O
Show the answer

A. Each I/O brings at most BB new items into memory, and comparing the query with them leaves at most B+1B + 1 possible intervals, so each I/O divides the N+1N + 1 outcomes by at most B+1B + 1

It is an information argument: log⁡B+1(N+1)\log_{B+1}(N+1) divisions by at most B+1B + 1 are needed to isolate one of N+1N + 1 outcomes. B-trees and the van Emde Boas layout reach it up to a constant factor.

Question 3

The van Emde Boas layout searches in O(log⁡BN)O(\log_B N) transfers for every block size BB. What does it give up against a B-tree tuned to one known BB?

  1. Nothing: both need exactly log⁡BN+O(1)\log_B N + O(1) transfers
  2. A constant factor: no cache-oblivious search structure can guarantee fewer than lg⁡e⋅log⁡BN≈1.44log⁡BN\lg e \cdot \log_B N \approx 1.44 \log_B N transfers, while a B-tree needs log⁡BN+O(1)\log_B N + O(1)
  3. A factor of log⁡2B\log_2 B, like binary search
  4. It cannot support search at all once BB exceeds N\sqrt N
Show the answer

B. A constant factor: no cache-oblivious search structure can guarantee fewer than lg⁡e⋅log⁡BN≈1.44log⁡BN\lg e \cdot \log_B N \approx 1.44 \log_B N transfers, while a B-tree needs log⁡BN+O(1)\log_B N + O(1)

Bender, Brodal, Fagerberg, Ge, He, Hu, Iacono and López-Ortiz (2003) proved the lg⁡e\lg e lower bound, a provable separation between knowing BB and not knowing it; randomized variants of the layout approach it.

Question 4

What does the tall-cache assumption M=Ω(B2)M = \Omega(B^2) say, and where is it known to be necessary?

  1. The cache holds at least about as many lines as a line holds words; without it, no cache-oblivious comparison-based sort is optimal for all MM and BB
  2. The cache must be at least as large as one block; scanning needs it
  3. Cache lines must be taller than they are wide; transposition needs it
  4. The data must fit in B2B^2 words; searching needs it
Show the answer

A. The cache holds at least about as many lines as a line holds words; without it, no cache-oblivious comparison-based sort is optimal for all MM and BB

M=Ω(B2)M = \Omega(B^2) means M/B=Ω(B)M/B = \Omega(B) lines. Brodal and Fagerberg (2003) proved that optimal cache-oblivious comparison-based sorting needs such an assumption, and that even with it, no cache-oblivious algorithm permutes optimally for all MM and BB.

Further reading

  • A. Aggarwal & J. S. Vitter, "The input/output complexity of sorting and related problems," Communications of the ACM 31(9) (1988), 1116–1127.
  • M. Frigo, C. E. Leiserson, H. Prokop & S. Ramachandran, "Cache-oblivious algorithms," Proceedings of FOCS (1999); journal version in ACM Transactions on Algorithms 8(1) (2012).
  • M. A. Bender, E. D. Demaine & M. Farach-Colton, "Cache-oblivious B-trees," SIAM Journal on Computing 35(2) (2005), 341–358; first presented at FOCS 2000.
  • G. S. Brodal & R. Fagerberg, "On the limits of cache-obliviousness," Proceedings of STOC (2003).
  • J. S. Vitter, "Algorithms and data structures for external memory," Foundations and Trends in Theoretical Computer Science 2(4) (2008).