External sorting (code by Claude, guidance by Georgios Evangelidis)
A file of N pages is sorted with only B pages of memory. Pass 0 reads the file in chunks, sorts each chunk in memory and writes it back as a sorted run. Every later pass merges several runs into one, reading each run a page at a time into an input buffer and collecting the merged output in one output buffer. Every pass reads and writes the whole file, so the cost is 2N page I/Os per pass.
Passes
| Pass | Input runs | Output runs (pages each) | Reads | Writes |
|---|
Cost
Reading the diagram
Things to try
Step through pass 0 of the two-way sort, then switch to external merge sort with B = 3 on the same file: pass 0 now makes runs of 3 pages, and one pass disappears.
Generate a 30-page file and raise B from 3 to 6: the number of passes, and so the I/O cost, drops quickly because it grows with logB−1.
With replacement selection, watch records that are smaller than the last one written get frozen; on random data runs come out about twice as long as the current set.
Load an already sorted file (1-60) and use replacement selection: pass 0 produces a single run.