How would you sort a 2 GB file of records on a machine with only about 100 MB of free memory?
MediumSorting
Content review
Report an errorNot yet reviewed
Show model answer
Use external merge sort. Phase one reads the file in chunks that fit in memory (say 80 MB each, about 25 chunks), sorts each chunk with an in-memory sort and writes it back as a sorted run. Phase two performs a k-way merge: open all runs, keep a small read buffer for each plus a min-heap holding the current head record of every run, repeatedly output the smallest and refill from that run.
Total work is O(N log N) comparisons, but the cost that matters is I/O: each record is read and written about twice. If there are too many runs for one merge (not enough memory for buffers), merge in several passes. Larger sequential buffers, replacement selection (which produces runs about twice the memory size) and using a separate output disk all reduce I/O time.