Sub topic 13
External Merge Sort for Data Larger Than Memory
This chapter assumes you know the merge step, bottom-up merge sort, and Python's heapq module. Suppose you need to sort 200 GB of log records on a machine with 8 GB of RAM. In-memory merge sort cannot help, because it needs the whole array plus an auxiliary buffer in memory. External merge sort fixes this by doing the expensive work on disk while keeping only small pieces in RAM.
The Two Phases
External merge sort is organized around disk I/O, since reading and writing disk costs far more than comparisons.
- Run formation. Read as much data as fits in memory (a chunk), sort it in RAM with any fast sort, and write it back to disk as a sorted file called a run. Repeat until the input is used up.
- K-way merge. Open all runs at once. Keep the current front element of each run in a min-heap. Repeatedly pop the smallest element, write it to the output, and push the next element from the same run.
The k-way merge generalizes the two-way merge from earlier chapters. A heap of size k finds the minimum in O(log k) time instead of comparing all k fronts, so merging n total elements costs O(n log k).
A Working Implementation
This version sorts a file of integers, one per line. chunk_size stands in for the memory limit.
import heapq
import os
import random
import tempfile
def write_run(sorted_chunk, directory):
fd, path = tempfile.mkstemp(dir=directory, suffix=".run", text=True)
with os.fdopen(fd, "w") as f:
for x in sorted_chunk:
f.write(f"{x}\n")
return path
def read_run(path):
with open(path) as f:
for line in f:
yield int(line)
def external_sort(input_path, output_path, chunk_size, directory):
# Phase 1: run formation
run_paths = []
with open(input_path) as f:
chunk = []
for line in f:
chunk.append(int(line))
if len(chunk) == chunk_size:
chunk.sort()
run_paths.append(write_run(chunk, directory))
chunk = []
if chunk:
chunk.sort()
run_paths.append(write_run(chunk, directory))
# Phase 2: k-way merge
readers = [read_run(p) for p in run_paths]
heap = []
for idx, reader in enumerate(readers):
first = next(reader, None)
if first is not None:
heap.append((first, idx))
heapq.heapify(heap)
with open(output_path, "w") as out:
while heap:
value, idx = heapq.heappop(heap)
out.write(f"{value}\n")
nxt = next(readers[idx], None)
if nxt is not None:
heapq.heappush(heap, (nxt, idx))
for p in run_paths:
os.remove(p)
return len(run_paths)
random.seed(0)
with tempfile.TemporaryDirectory() as tmp:
data = [random.randint(0, 10**6) for _ in range(10_000)]
src = os.path.join(tmp, "input.txt")
dst = os.path.join(tmp, "output.txt")
with open(src, "w") as f:
f.writelines(f"{x}\n" for x in data)
runs = external_sort(src, dst, chunk_size=1_000, directory=tmp)
with open(dst) as f:
result = [int(line) for line in f]
print(runs, result == sorted(data)) # 10 TrueThe heap stores (value, run_index) tuples. When values are equal, the lower run index wins. Runs come from the input in order, and list.sort is stable, so the whole external sort stays stable. In production you can use heapq.merge(*readers), which does the same job.
Counting Passes
Each pass reads and writes the entire dataset, so the number of passes determines the running time. With N bytes of data and M bytes of memory, run formation produces about N/M runs. You cannot always merge them all at once, because each open run needs an input buffer of B bytes. The maximum fan-in is therefore about M/B − 1, with one buffer kept for output.
If there are more runs than the fan-in k allows, merge them in groups and repeat. The total number of passes is roughly:
| Phase | Passes over the data |
|---|---|
| Run formation | 1 |
| Merging | ⌈log_k(N/M)⌉ |
Exercises
Exercise
You must sort 100 GB with 1 GB of memory, and buffer sizes limit the merge fan-in to 50. How many full passes over the data does the sort make, counting run formation?
Show answer
Run formation makes 100 runs in 1 pass. The first merge pass combines groups of 50 into 2 runs. The second merge pass combines those 2 into 1. The total is 3 passes.
Exercise
Why does the heap entry include the run index instead of only the value?
Show answer
When two runs have equal front values, the index breaks the tie in favor of the earlier run. Earlier runs hold earlier input, so equal records keep their original order and the sort stays stable. For records that cannot be compared directly, the index also keeps the tuple comparison from ever reaching the payload.