Simple Algorithm
Algorithms & Data Structures · Optimal · 26 min

External Sorting

Sorting data that does not fit in memory: runs, multiway merges and the I/O bound.

When the data is a thousand times larger than memory, comparisons stop mattering; what costs is moving blocks between disk and memory. External merge sort sorts a terabyte with a few gigabytes of memory in two passes over the data, and Aggarwal and Vitter proved in 1988 that, up to a constant factor, no algorithm can move fewer blocks.

What you’ll learn

  • Model external computation with NN records, memory MM, blocks of BB records and block transfers, and state the sorting bound Θ(NBlog⁡M/BNB)\Theta\big(\frac{N}{B} \log_{M/B} \frac{N}{B}\big).
  • Form runs by sorting memory loads or by replacement selection, whose runs average 2M2M on random input (the snowplow argument).
  • Merge M/B−1M/B - 1 runs per pass with a heap or a tournament tree, and count the passes and block transfers.
  • Prove the lower bound by counting orders, and relate it to distribution sort and to cache-oblivious funnelsort with its tall-cache assumption.

Counting block transfers

Internal algorithms behave badly in this model. Quicksort and heapsort jump around the array, and on disk a jump can cost a whole I/O for a single record. Binary merge sort scans sequentially, but after the memory-sized pieces are sorted it still needs ⌈log⁡2(N/M)⌉\lceil \log_2 (N/M) \rceil merge passes, each reading and writing all the data. The right algorithm merges many runs at once, and it meets this bound:

A concrete case: a terabyte of records (N=1012N = 10^{12} bytes), M=8M = 8 GB of memory and blocks of B=1B = 1 MB. Sorting memory loads produces ⌈N/M⌉=125\lceil N/M \rceil = 125 sorted runs, and memory holds M/B=8,000M/B = 8{,}000 blocks, enough to merge all 125 runs at once. The whole sort reads and writes the data twice: 4×1064 \times 10^6 block transfers, and every one of them is a large sequential transfer.

Predict before you look

In that example, how many passes over the data (reading and writing all of it) does the sort make in total, counting the pass that forms the runs?

Show the answer

2

One pass forms 125 runs, and since up to 7,999 runs can be merged at once (one input block per run plus an output block), a single merge pass finishes: 2 passes. With binary merges, the 125 runs would need ⌈log⁡2125⌉=7\lceil \log_2 125 \rceil = 7 merge passes.

Forming runs: memory loads and replacement selection

The simplest way to form runs reads MM records, sorts them in memory, writes them out, and repeats: ⌈N/M⌉\lceil N/M \rceil runs of length MM, for one read and one write of the data.

Replacement selection makes longer runs from the same memory. Keep MM records in a min-heap. Repeatedly output the smallest record that is at least the last one output, and read the next input record into the freed slot. A new record smaller than the last output cannot join the current run, so it is tagged for the next run. On sorted input this produces a single run, on reversed input runs of exactly MM, and on random input runs that average 2M2M.

python
import heapq

def replacement_selection(stream, M):
    """Split a stream of keys into sorted runs, holding at most M keys in memory."""
    it = iter(stream)
    heap = [(0, x) for _, x in zip(range(M), it)]     # (run number, key)
    heapq.heapify(heap)
    runs, current = [], []
    while heap:
        run, x = heapq.heappop(heap)
        if run > len(runs):                           # the current run is finished
            runs.append(current); current = []
        current.append(x)
        nxt = next(it, None)
        if nxt is not None:                           # a key smaller than x must wait
            heapq.heappush(heap, (run + (nxt < x), nxt))   # for the next run
    if current:
        runs.append(current)
    return runs

Ordering the heap by (run number, key) keeps the records of the next run below every record of the current one. On random keys, the inner runs averaged 2.003M2.003M for M=100M = 100 and 1.996M1.996M for M=1000M = 1000; sorted input gave one run and reversed input runs of exactly MM.

DerivationWhy 2M: the snowplow
  1. The picture (Knuth). Think of the keys as snow falling uniformly on a circular road, and of the output position as a snowplow that clears the snow where it stands while driving around. Every record output is replaced by a new random key, so snow falls exactly as fast as it is cleared, and the road always holds MM units of snow.

  2. M  =  12⋅h⋅1(road of length 1)M \;=\; \tfrac12 \cdot h \cdot 1 \qquad (\text{road of length } 1)

    Steady state. The snow just ahead of the plow has been falling since the plow last passed there, a whole lap ago, while the snow just behind it has only just started to fall. So the depth grows linearly around the road from 0 behind the plow to some maximum hh in front of it: a wedge whose area is the memory:

  3. run length  =  h  =  2M\text{run length} \;=\; h \;=\; 2M

    One lap is one run. During one lap the plow clears the full depth hh at every point of the road, so it outputs hh records before it comes back to its starting point and a new run begins:

Longer runs mean fewer runs, which can save a whole merge pass when N/MN/M is just above the merge fan-in. The price is heap overhead and runs of varying length, and many systems simply sort memory loads with a fast internal sort, because with today's memories one merge pass usually suffices anyway.

Multiway merging and the number of passes

A multiway merge combines kk runs at once. Memory holds one input block per run and one output block, so the fan-in can be k=M/B−1k = M/B - 1. A min-heap of the kk front records picks each output record with O(log⁡k)O(\log k) comparisons; a tournament tree of losers, the classic choice, needs at most ⌈log⁡2k⌉\lceil \log_2 k \rceil. When a run's input block is used up, the next block of that run is read; when the output block is full, it is written. Every pass reads and writes each record once: 2N/B2N/B I/Os per pass.

python
import heapq

def kway_merge(runs):
    """Merge k sorted lists with a min-heap of their front elements: O(log k) per element."""
    heap = [(r[0], i, 0) for i, r in enumerate(runs) if r]
    heapq.heapify(heap)
    out = []
    while heap:
        x, i, j = heapq.heappop(heap)
        out.append(x)
        if j + 1 < len(runs[i]):
            heapq.heappush(heap, (runs[i][j + 1], i, j + 1))
    return out

In memory for clarity; an external version reads each run block by block. Tested on the runs produced by replacement_selection. The run index ii in each heap entry breaks ties between equal keys in favor of the earlier run, which keeps the merge stable.

DerivationPasses and block transfers
  1. merge passes=⌈log⁡kR⌉=⌈log⁡M/B−1NM⌉\text{merge passes} = \left\lceil \log_{k} R \right\rceil = \left\lceil \log_{M/B - 1} \frac{N}{M} \right\rceil

    Passes. Run formation leaves R=⌈N/M⌉R = \lceil N/M \rceil runs, and each merge pass divides the number of runs by the fan-in k=M/B−1k = M/B - 1:

  2. I/Os=2 NB(1+⌈log⁡M/B−1NM⌉)\text{I/Os} = 2\,\frac{N}{B} \left(1 + \left\lceil \log_{M/B - 1} \frac{N}{M} \right\rceil\right)

    I/Os. Every pass, including run formation, reads and writes all N/BN/B blocks:

  3. 1+log⁡M/BNM  =  log⁡M/BMB+log⁡M/BNM  =  log⁡M/BNB1 + \log_{M/B} \frac{N}{M} \;=\; \log_{M/B} \frac{M}{B} + \log_{M/B} \frac{N}{M} \;=\; \log_{M/B} \frac{N}{B}

    It meets the bound. The pass that forms runs is worth exactly one more level of the logarithm, so for M/B≥3M/B \ge 3 the total is within a constant factor of sort(N)\mathrm{sort}(N):

Two engineering ideas hide the remaining cost. Double buffering reads the next block of a run while the current one is being merged, and forecasting (Knuth) predicts which run will empty its buffer first by comparing the last keys of the buffers, so that block can be fetched in advance. Historically, when data lived on tapes that could only be read in order, polyphase merging (Gilstad, 1960) spread the runs unevenly over the tape drives, in Fibonacci-like numbers, so that few drives sat idle.

Check your understanding

Run formation produced 1,000 runs, and memory holds 100 blocks, so the fan-in is 99. How many merge passes follow?

  1. 1
  2. 2
  3. 10
  4. 1,000
Show the answer

B. 2

After one pass, ⌈1000/99⌉=11\lceil 1000/99 \rceil = 11 runs remain, and a second pass merges them: ⌈log⁡991000⌉=2\lceil \log_{99} 1000 \rceil = 2, since 99<1000≤992=9,80199 < 1000 \le 99^2 = 9{,}801. Binary merging would need ⌈log⁡21000⌉=10\lceil \log_2 1000 \rceil = 10 passes.

The lower bound, and beyond

DerivationProof by counting orders (sketch)
  1. #{orders distinguishable after t reads}  ≤  (B!)N/B(MB)t\#\{\text{orders distinguishable after } t \text{ reads}\} \;\le\; (B!)^{N/B} \binom{M}{B}^{t}

    What one read can reveal. Reading a block brings BB records into a memory that holds at most M−BM - B others. Comparisons can then reveal how the newcomers interleave with the residents, one of at most (MB)\binom{M}{B} possibilities, and, the first time that block is read, the newcomers' own order, one of B!B!. Only N/BN/B blocks are ever read for the first time, and writes reveal nothing new:

  2. N!  ≤  (B!)N/B(MB)tN! \;\le\; (B!)^{N/B} \binom{M}{B}^{t}

    Sorting must tell all orders apart. Each of the N!N! input orders needs its own outcome:

  3. t  ≳  Nlog⁡(N/B)Blog⁡(eM/B)  =  Ω ⁣(NBlog⁡M/BNB)t \;\gtrsim\; \frac{N \log (N/B)}{B \log (eM/B)} \;=\; \Omega\!\left(\frac{N}{B} \log_{M/B} \frac{N}{B}\right)

    Solve for tt. Up to lower-order terms, log⁡N!−NBlog⁡B!≈Nlog⁡(N/B)\log N! - \tfrac{N}{B} \log B! \approx N \log (N/B) (for N=106N = 10^6 and B=103B = 10^3, the two sides differ by under 0.1%), and log⁡(MB)≤Blog⁡(eM/B)\log \binom{M}{B} \le B \log (eM/B):

Distribution sort is the mirror image of merge sort and meets the same bound: choose about M/BM/B splitters from a random sample, scatter the records into that many buckets in one pass, with one output block per bucket, and recurse on each bucket; Vitter's survey covers both approaches.

Cache-oblivious sorting asks for the bound at every level of a memory hierarchy at once, without the algorithm knowing MM or BB. Funnelsort (Frigo, Leiserson, Prokop & Ramachandran, 1999) achieves it under the tall-cache assumption M=Ω(B2)M = \Omega(B^2), and Brodal and Fagerberg (2003) proved that no cache-oblivious algorithm can sort optimally without some assumption of this kind.

The Sort Benchmark (sortbenchmark.org) began with the Datamation sort defined in 1985, one million 100-byte records, and was run by Jim Gray until 2007. Its categories today include GraySort (the rate of sorting at least 100 TB), MinuteSort (the most data sorted in 60 seconds), JouleSort (energy) and CloudSort (cost on a public cloud), each with a general-purpose "Daytona" and a specialized "Indy" class.

Key takeaways

  • In the external-memory model the cost is block transfers, and sorting needs Θ(NBlog⁡M/BNB)\Theta\big(\frac{N}{B} \log_{M/B} \frac{N}{B}\big) I/Os, a small multiple of a scan in practice.
  • Runs come from sorting memory loads (N/MN/M runs of MM) or from replacement selection, whose runs average 2M2M on random input by the snowplow argument and cover sorted input in one run.
  • Merging M/B−1M/B - 1 runs per pass takes 1+⌈log⁡M/B−1(N/M)⌉1 + \lceil \log_{M/B - 1} (N/M) \rceil passes in all, which matches the bound because 1+log⁡M/B(N/M)=log⁡M/B(N/B)1 + \log_{M/B}(N/M) = \log_{M/B}(N/B); one merge pass usually suffices.
  • Counting the orders each I/O can reveal proves the lower bound; distribution sort meets it too, and funnelsort meets it cache-obliviously under a tall-cache assumption that cannot be dropped.

Check yourself

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

Question 1

Replacement selection runs with memory for MM records on a long input of random keys. How long are its runs on average?

  1. MM
  2. 2M2M
  3. Mlog⁡2MM \log_2 M
  4. M\sqrt{M}
Show the answer

B. 2M2M

The snowplow argument: in steady state the unsorted keys form a wedge of area MM ahead of the output position, and one lap of the output position, one run, clears the wedge's full height 2M2M. Sorting memory loads gives exactly MM.

Question 2

N=240N = 2^{40} records, M=230M = 2^{30} records of memory and blocks of B=220B = 2^{20} records. About how many I/Os does sort(N)=NBlog⁡M/BNB\mathrm{sort}(N) = \frac{N}{B} \log_{M/B} \frac{N}{B} give?

  1. NBlog⁡2NB=20⋅220\frac{N}{B} \log_2 \frac{N}{B} = 20 \cdot 2^{20}
  2. 2⋅2202 \cdot 2^{20}, about two scans of the data
  3. Nlog⁡2N=40⋅240N \log_2 N = 40 \cdot 2^{40}
  4. 2202^{20}, a single scan
Show the answer

B. 2⋅2202 \cdot 2^{20}, about two scans of the data

N/B=220N/B = 2^{20} and M/B=210M/B = 2^{10}, so log⁡M/B(N/B)=20/10=2\log_{M/B}(N/B) = 20/10 = 2, and the bound is about two scans' worth of I/Os, up to its constant factor. Binary merging would cost log⁡2(N/B)=20\log_2(N/B) = 20 scans' worth, ten times more.

Question 3

Funnelsort sorts with the optimal number of I/Os without knowing MM or BB. Under which assumption?

  1. The input is uniformly random
  2. The cache is tall: M=Ω(B2)M = \Omega(B^2), an assumption that Brodal and Fagerberg showed no cache-oblivious sort can drop entirely
  3. B=1B = 1
  4. The data fits in memory
Show the answer

B. The cache is tall: M=Ω(B2)M = \Omega(B^2), an assumption that Brodal and Fagerberg showed no cache-oblivious sort can drop entirely

Frigo, Leiserson, Prokop and Ramachandran (1999) proved funnelsort optimal under the tall-cache assumption, and Brodal and Fagerberg (2003) proved that optimal cache-oblivious sorting is impossible without some such assumption.

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.
  • D. E. Knuth, The Art of Computer Programming, Vol. 3: Sorting and Searching, 2nd ed. (Addison-Wesley, 1998), §5.4.
  • J. S. Vitter, "External memory algorithms and data structures: dealing with massive data," ACM Computing Surveys 33(2) (2001).
  • M. Frigo, C. E. Leiserson, H. Prokop & S. Ramachandran, "Cache-oblivious algorithms," Proceedings of the 40th IEEE Symposium on Foundations of Computer Science (1999).
  • G. S. Brodal & R. Fagerberg, "On the limits of cache-obliviousness," Proceedings of the 35th ACM Symposium on Theory of Computing (2003).