File Sorting & Merging
A file may be larger than memory, so sorting must be external. The trick is to create sorted runs, then merge them without loading the whole file.
In plain English
External sorting is sorting a huge pile of cards by making small sorted piles, then merging them.
By the end you will be able to
- Explain external merge sort.
- Trace the run creation and merge phases.
- Know why merging is I/O-bound.
- Estimate the number of passes.
Sorted runs
Read as much of the file as fits in memory, sort that chunk, and write it back as a sorted run. Repeat until the whole file is a set of runs. Each run is internally sorted, but the file as a whole is not. The number of runs depends on the file size and the memory buffer.
chunk 1 -> sort -> run1
chunk 2 -> sort -> run2
chunk 3 -> sort -> run3Merging runs
Merge two or more sorted runs by repeatedly taking the smallest front record. A two-way merge uses two input buffers and one output buffer. A k-way merge uses k input buffers and is faster when memory allows. Each merge pass reads and writes the whole file, so the I/O cost grows with the number of passes.
merge(run1, run2):
while both have records:
output the smaller front record
append the remaining recordsCost
External sorting is dominated by disk I/O, not comparisons. More memory means fewer runs and fewer merge passes. A large k-way merge can reduce the number of passes to one or two. The final sorted file is written once, and intermediate runs are deleted.
Watch it happen
Step through the worked example. Play it, pause it, or move one step at a time.
step-by-step
Step 1 of 6
Read chunk 1 and sort it
Chunk 1 fits in memory. Sort it and write it back as run 1.
Key takeaways
- External sorting creates sorted runs that fit in memory.
- Merging combines runs without loading the whole file.
- The cost is dominated by I/O passes.
- More memory means fewer runs and fewer passes.
- A k-way merge can reduce the number of passes.
Common pitfalls
- Trying to sort the whole file in memory.
- Ignoring the cost of writing intermediate runs.
- Assuming comparisons dominate external sorting.
Kernel notes
- Explain run creation.
- Trace a two-way merge.
- Relate memory size to the number of passes.
Quick check
1. Why does external sorting create runs?
2. What dominates the cost of external sorting?