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 records, memory , blocks of records and block transfers, and state the sorting bound .
- Form runs by sorting memory loads or by replacement selection, whose runs average on random input (the snowplow argument).
- Merge 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 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 ( bytes), GB of memory and blocks of MB. Sorting memory loads produces sorted runs, and memory holds blocks, enough to merge all 125 runs at once. The whole sort reads and writes the data twice: block transfers, and every one of them is a large sequential transfer.
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 merge passes.
Forming runs: memory loads and replacement selection
The simplest way to form runs reads records, sorts them in memory, writes them out, and repeats: runs of length , for one read and one write of the data.
Replacement selection makes longer runs from the same memory. Keep 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 , and on random input runs that average .
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 runsOrdering 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 for and for ; sorted input gave one run and reversed input runs of exactly .
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 units of snow.
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 in front of it: a wedge whose area is the memory:
One lap is one run. During one lap the plow clears the full depth at every point of the road, so it outputs 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 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 runs at once. Memory holds one input block per run and one output block, so the fan-in can be . A min-heap of the front records picks each output record with comparisons; a tournament tree of losers, the classic choice, needs at most . 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: I/Os per pass.
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 outIn memory for clarity; an external version reads each run block by block. Tested on the runs produced by replacement_selection. The run index in each heap entry breaks ties between equal keys in favor of the earlier run, which keeps the merge stable.
Passes. Run formation leaves runs, and each merge pass divides the number of runs by the fan-in :
I/Os. Every pass, including run formation, reads and writes all blocks:
It meets the bound. The pass that forms runs is worth exactly one more level of the logarithm, so for the total is within a constant factor of :
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.
Run formation produced 1,000 runs, and memory holds 100 blocks, so the fan-in is 99. How many merge passes follow?
- 1
- 2
- 10
- 1,000
Show the answer
B. 2
After one pass, runs remain, and a second pass merges them: , since . Binary merging would need passes.
The lower bound, and beyond
What one read can reveal. Reading a block brings records into a memory that holds at most others. Comparisons can then reveal how the newcomers interleave with the residents, one of at most possibilities, and, the first time that block is read, the newcomers' own order, one of . Only blocks are ever read for the first time, and writes reveal nothing new:
Sorting must tell all orders apart. Each of the input orders needs its own outcome:
Solve for . Up to lower-order terms, (for and , the two sides differ by under 0.1%), and :
Distribution sort is the mirror image of merge sort and meets the same bound: choose about 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 or . Funnelsort (Frigo, Leiserson, Prokop & Ramachandran, 1999) achieves it under the tall-cache assumption , 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 I/Os, a small multiple of a scan in practice.
- Runs come from sorting memory loads ( runs of ) or from replacement selection, whose runs average on random input by the snowplow argument and cover sorted input in one run.
- Merging runs per pass takes passes in all, which matches the bound because ; 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.
Replacement selection runs with memory for records on a long input of random keys. How long are its runs on average?
Show the answer
B.
The snowplow argument: in steady state the unsorted keys form a wedge of area ahead of the output position, and one lap of the output position, one run, clears the wedge's full height . Sorting memory loads gives exactly .
records, records of memory and blocks of records. About how many I/Os does give?
- , about two scans of the data
- , a single scan
Show the answer
B. , about two scans of the data
and , so , and the bound is about two scans' worth of I/Os, up to its constant factor. Binary merging would cost scans' worth, ten times more.
Funnelsort sorts with the optimal number of I/Os without knowing or . Under which assumption?
- The input is uniformly random
- The cache is tall: , an assumption that Brodal and Fagerberg showed no cache-oblivious sort can drop entirely
- The data fits in memory
Show the answer
B. The cache is tall: , 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).