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.

File contents (sort keys, up to 120)
Random file
Step 0 of 0
start
Pass 0 Pages N 0 Page reads 0 Page writes 0 Total I/O so far 0 Formula predicts 0

Passes

PassInput runsOutput runs (pages each)ReadsWrites

Cost

Reading the diagram

A page of a run on disk; each run has its own colour
A page already read in this pass
Output buffer in memory
Records being compared
Record just moved, or page just read or written
Replacement selection: frozen record, waiting for the next run

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.