
This article is part of a series adapted and expanded from my Medium article, published August 5, 2024, and my merge sort repository.
Merge sort can also handle data that does not fit in memory. This lesson explains runs and balanced merging.

Follow the animation step by step
The animation uses four blocks that fit in memory one at a time. It shows why external merge sort creates sorted runs first, then combines them.
- Read manageable blocks: the unsorted blocks are [9, 3], [8, 1], [7, 2], and [6, 4]. Only a block is held in memory at once.
- Sort and write runs: sort each block and save it back as a run: [3, 9], [1, 8], [2, 7], and [4, 6]. A run is a sequential piece of data that is already sorted.
- Start merging with the smallest heads: compare the first unread value of every run. The smallest is 1, then 2, then 3, then 4. The animation shows these values entering the output buffer while each run's read position advances.
- Continue through the runs: keep selecting the smallest available head. This eventually writes [1, 2, 3, 4, 6, 7, 8, 9].
- Use balanced passes: with many runs, merge them in similarly sized groups. Each pass creates longer runs and avoids repeatedly merging one growing file with every other run.
In a real external sort, buffers collect reads and writes into larger sequential operations. That reduces expensive small disk operations.

External sorting and sorted runs
When a file is too large to fit in memory, external merge sort works with smaller sorted pieces called runs:
- Read a block that fits in memory, sort it, and write it as a run.
- Repeat until the input has been read.
- Merge the runs into larger sorted runs, using buffers to read and write data in blocks.
- Continue until one sorted output remains.
This reduces the need for random disk access. The choice of merge strategy and buffer sizes affects how many times the data must be read and written.
Balanced merge and a four-way example
A balanced merge combines runs in roughly even groups. In a two-way merge, each operation combines two runs. In a four-way merge, it combines four runs at once. For example:
[1, 7] [2, 8] [3, 6] [4, 5]
↓ four-way merge
[1, 2, 3, 4, 5, 6, 7, 8]At each step, choose the smallest current item among the runs. A priority queue is useful when there are many input runs. A larger merge width can reduce the number of passes, but it also needs more input buffers and open streams. Historically, tape drives made these limits especially important: three or four tapes could be used, while more drives allowed different merge arrangements.


