Capstone: Quarry's Compactor
In short: Every lesson in this section answered one piece of "sort more, and sort it
smarter": heap sort's in-place O(n log n), non-comparison sorts that skip
comparing entirely, quickselect's one-sided search, the proof that no
comparison sort can do better than n log n in the worst case, and external
sorting's runs-then-merge shape for data bigger than memory. Quarry's
compactor is where the last piece — external sorting — becomes a real,
repeatable job: it doesn't just merge once, it keeps merging in rounds
until a growing batch of records collapses into a single sorted file, and it
reports exactly how many disk passes that cost.
What you're building
compactor(records, memory_limit, fan_in) -> {"sorted": [...], "runs": r, "passes": p}compactor([5, 3, 8, 1, 9, 2, 7, 4, 6], 3, 3)
# {"sorted": [1, 2, 3, 4, 5, 6, 7, 8, 9], "runs": 3, "passes": 2}sorted: every record, fully sorted ascending.runs: how many sorted runsrecordssplit into after generation —ceil(len(records) / memory_limit).passes: total disk passes — 1 for generation, plus one more per merge round, where each round foldsfan_inruns into one until a single run remains.
This is external sorting from the last lesson, generalized: instead of one
merge over every run at once, the compactor merges fan_in runs per round —
useful when there genuinely isn't room to hold every run's front item open at
the same time.