Sub topic 13
External Merge Sort for Data Larger Than Memory
Every merge sort in the earlier chapters assumed the whole input fits in RAM. This chapter drops that assumption. It assumes you already know the two-way merge, bottom-up merge sort (merging runs of growing width), and Big-O notation. It also assumes you can read and write files in Python and know roughly what a binary heap does.
External merge sort is the standard way to sort data stored on disk or SSD when the data is much larger than available memory. Database engines use it for ORDER BY and sort-merge joins. The Unix sort command and big-data shuffle stages such as those in MapReduce and Spark also use it.
Why the In-Memory Version Breaks
Suppose you have 100 GB of records and 1 GB of RAM. The recursive version cannot even load the input. A naive fix is to memory-map the file and run ordinary merge sort on it, but that performs badly. Each two-way merge pass reads and writes the entire file. With n records you need about log₂ n passes, so about 37 full passes over the data for a billion records. Random access to the mapped file also causes page faults that the operating system cannot predict.
On external storage the cost that matters is the number of block transfers between disk and memory, not the number of comparisons. A comparison takes nanoseconds. Even a sequential read of a block takes microseconds, and a random seek on a spinning disk takes milliseconds. External merge sort is designed to keep I/O sequential and to make as few passes as possible.
The Two Phases
The algorithm has two phases.
- Run generation. Read as much of the input as fits in memory (M records), sort that chunk in memory with any fast sort, and write it out as a sorted file called a run. Repeat until the input is used up. This gives about N/M runs.
- Merging. Merge k runs at a time into one longer run with a k-way merge. Repeat until a single run remains. That run is the sorted output.
This is the bottom-up merge sort from an earlier chapter with two changes. The first runs are memory-sized instead of length 1, and each pass merges k runs at a time instead of 2.
The k-Way Merge
A two-way merge compares the heads of two lists. A k-way merge has to find the smallest of k heads, and checking them one by one costs O(k) per output record. A min-heap that holds one entry per run brings this down to O(log k). Each step works like this:
- Look at the smallest entry on the heap and write it to the output.
- Read the next record from the run that entry came from.
- Put that record on the heap in place of the old entry. If the run is empty, pop the entry instead.
Merging N records across k runs costs O(N log k) comparisons. Every run is read from front to back, so all the I/O is sequential. Each run only needs an input buffer, and the output needs one more buffer.
A Complete Implementation
The program below sorts a text file with one integer per line. max_items stands in for the memory limit and fan_in is k. When there are more runs than fan_in, the program runs extra intermediate merge passes.
import heapq
import os
import random
import tempfile
def write_run(sorted_values, directory):
fd, path = tempfile.mkstemp(dir=directory, suffix=".run", text=True)
with os.fdopen(fd, "w") as f:
for v in sorted_values:
f.write(f"{v}\n")
return path
def create_runs(input_path, max_items, directory):
"""Phase 1: read memory-sized chunks, sort each, write each as a run."""
runs = []
chunk = []
with open(input_path) as f:
for line in f:
chunk.append(int(line))
if len(chunk) == max_items:
chunk.sort()
runs.append(write_run(chunk, directory))
chunk = []
if chunk:
chunk.sort()
runs.append(write_run(chunk, directory))
return runs
def read_ints(path):
with open(path) as f:
for line in f:
yield int(line)
def k_way_merge(run_paths, output_path):
"""Merge several sorted run files into one sorted file using a min-heap."""
iterators = [read_ints(p) for p in run_paths]
heap = []
for run_index, it in enumerate(iterators):
first = next(it, None)
if first is not None:
heap.append((first, run_index))
heapq.heapify(heap)
with open(output_path, "w") as out:
while heap:
value, run_index = heap[0]
out.write(f"{value}\n")
nxt = next(iterators[run_index], None)
if nxt is None:
heapq.heappop(heap)
else:
heapq.heapreplace(heap, (nxt, run_index))
def external_sort(input_path, output_path, max_items, fan_in):
"""Sort input_path into output_path. Returns the number of merge passes."""
with tempfile.TemporaryDirectory() as tmp:
runs = create_runs(input_path, max_items, tmp)
if not runs:
open(output_path, "w").close()
return 0
passes = 0
while len(runs) > fan_in:
next_runs = []
for g in range(0, len(runs), fan_in):
group = runs[g:g + fan_in]
fd, merged_path = tempfile.mkstemp(dir=tmp, suffix=".run")
os.close(fd)
k_way_merge(group, merged_path)
for p in group:
os.remove(p)
next_runs.append(merged_path)
runs = next_runs
passes += 1
k_way_merge(runs, output_path)
return passes + 1
if __name__ == "__main__":
random.seed(1)
data = [random.randint(0, 10**6) for _ in range(10_000)]
with tempfile.TemporaryDirectory() as work:
src = os.path.join(work, "input.txt")
dst = os.path.join(work, "output.txt")
with open(src, "w") as f:
f.writelines(f"{v}\n" for v in data)
merge_passes = external_sort(src, dst, max_items=500, fan_in=4)
result = list(read_ints(dst))
print(result == sorted(data), merge_passes) # True 3With 10,000 records and max_items=500, phase 1 writes 20 runs. With fan_in=4, the merge phase goes 20 → 5 → 2 → 1, which is three merge passes. That matches ⌈log₄ 20⌉ = 3.
Counting Passes and I/O
Let N be the number of records, M the number that fit in memory, and k the fan-in. Run generation produces ⌈N/M⌉ runs. Each merge pass divides the number of runs by k, so the merge phase takes ⌈log_k(N/M)⌉ passes. Every pass, including run generation, reads and writes the whole dataset once. Measured in blocks of B records, the total I/O is:
2 · (N/B) · (1 + ⌈log_k(N/M)⌉)
The fan-in comes from memory. Merging needs one input buffer per run and one output buffer, so k ≈ M/B − 1. Larger buffers reduce seeks but reduce k. Smaller buffers raise k but turn each read into a short, seek-heavy access. In practice buffers are a few hundred KB to a few MB each.
Here is the earlier example with real numbers: 100 GB of data, 1 GB of memory, and 4 MB buffers.
| Setting | Runs after phase 1 | Fan-in k | Merge passes | Total data moved |
|---|---|---|---|---|
| Two-way merging | 100 | 2 | 7 | 1.6 TB |
| Fan-in 10 | 100 | 10 | 2 | 600 GB |
| Fan-in 250 (1 GB / 4 MB) | 100 | 250 | 1 | 400 GB |
The last row is the usual result. With realistic memory sizes, external merge sort almost always finishes in two passes over the data: one to create runs and one to merge them. In practice the cost is close to linear in N, even though the logarithm is still in the formula.
Making Runs Longer: Replacement Selection
Fewer runs means fewer merge passes, so longer initial runs help. Replacement selection generates runs with a heap of size M instead of sorting fixed chunks:
- Fill the heap with M records.
- Pop the smallest record and write it to the current run.
- Read the next input record. If it is at least as large as the record just written, it can still join the current run, so push it. Otherwise, mark it for the next run.
- When every record in the heap is marked for the next run, close the current run and start a new one.
On random input, runs average 2M records. On input that is already sorted, the whole file becomes a single run. On input sorted in reverse, every run has exactly M records. Replacement selection keeps the CPU busy while I/O is in progress. However, it does not keep equal keys in input order without extra tie-breaking, and sorting large chunks with a fast in-memory sort is often simpler and quick enough. Many modern systems use chunk sorting.
Common Errors and Gotchas
- Too many open files. A single merge of thousands of runs can hit the operating system's file-descriptor limit (often 1024). Cap the fan-in and run extra merge passes, as
external_sortdoes. - Unbuffered I/O. Reading one record per system call wastes the advantage of sequential access. Python's file objects buffer by default. In lower-level languages, read and write whole blocks yourself.
- Wrong memory estimate.
max_itemscounts records, but memory is measured in bytes. Python integers and objects take far more memory than their on-disk size. Measure, or size chunks by bytes. - Leftover temp files. A crash halfway through can leave gigabytes of runs on disk. Use a temporary directory that is cleaned up automatically, and delete runs once they have been merged.
- Assuming the comparison count dominates. An algorithm with fewer comparisons but more passes will lose on disk. Optimize for passes and sequential access first.
Where the Pattern Appears Again
The k-way heap merge is also useful when data fits in memory. Python's heapq.merge(*iterables) uses it to merge sorted streams lazily. Log-structured storage engines, such as LSM-tree databases, merge sorted files during compaction in the same way. Distributed sorts first range-partition the data across machines, then run external merge sort on each machine.
Exercise
You must sort 500 GB with 2 GB of memory and 8 MB I/O buffers, using fixed-size chunks for run generation. How many runs does phase 1 produce, what fan-in is available, and how many merge passes are needed?
Show answer
Phase 1 produces 500 / 2 = 250 runs. The fan-in is about 2 GB / 8 MB − 1 = 255 (256 buffers, with one kept for output). Since 250 ≤ 255, a single merge pass is enough, so the data is read and written twice in total, about 2 TB of I/O.
Exercise
In kwaymerge, why does the heap store (value, run_index) instead of just value? Give two separate reasons.
Show answer
First, the merge needs runindex to know which run to read the next record from after it outputs a value. Second, when values are equal, the runindex decides which entry comes first, so records from earlier runs (earlier in the input) come out first. This keeps the sort stable, and it also avoids comparing record objects that may not support ordering.
Exercise
With replacement selection and memory for M records, roughly how many runs do you get for (a) random input, (b) input that is already sorted, and (c) input in descending order, if there are N records?
Show answer
(a) About N/(2M) runs, because runs average 2M records. (b) One run, because every new record is at least as large as the last one written. (c) About N/M runs, because no incoming record can join the current run, so each run holds exactly M records.