How external mergesort sorts beyond memory

Short answer: External mergesort sorts runs that fit in memory, writes them out, and merges them k at a time. With R runs and a k-way merge, the number of full passes over the file is ⌈log_k R⌉. Replacement selection with a heap of M records produces runs whose expected length on random data is 2M, which cuts R. The cost that matters is the volume of reads and writes, not the comparisons inside a run.


What the problem actually asks

The file does not fit in memory. A comparison sort that randomly seeks in the file thrashes. The access pattern that disks and sequential scans reward is: read a memory-sized chunk, sort it, write a run, then merge several runs by always emitting the smallest current head. Each merge pass reads every record once and writes every record once.

How large a run the first phase can make determines how many merge passes follow. Filling a buffer and sorting it yields runs of length M. A heap that holds M records can do better on data that is not adversarial.


What the algorithm guarantees

Forming runs of length M from a file of N records produces R = ⌈N/M⌉ runs and uses one read and one write of the file. A k-way merge, limited by how many run heads fit in memory or how many streams the device can usefully read, reduces the run count by a factor k per pass. The pass count after the initial runs is ⌈log_k R⌉. Total I/O volume is about 2N times one plus that pass count, in units of records, plus bookkeeping.

Replacement selection keeps a min-heap of size M. The next input record joins the current run when it is at least the last record emitted, and otherwise waits in the heap for the next run. On random input the average run grows to about 2M, so R is about half of N/M. The merge of those runs is unchanged. A polyphase merge redistributes runs across fewer tapes by Fibonacci counts when the number of streams is the binding constraint.


The working steps

  1. Choose M from the memory budget and k from the number of sequential streams that can be read together while an output stream is written.
  2. Either sort successive buffers of M records into runs, or run replacement selection so that a new record extends the current run when it is ≥ the last output.
  3. Write the runs to external storage.
  4. Merge k runs at a time with a heap of the k current heads. Write one output run per merge. A head that is exhausted advances to the next record of that input run.
  5. Repeat the merge level until one run remains. That run is the sorted file.

The figure of merit is passes over external storage. An in-memory timsort or quicksort is the sort used inside a run, and it is not a substitute for the merge when N exceeds M. Replacement selection’s 2M expectation is for random records. Sorted input produces even longer runs. Adversarial input can hold the run length near M.


Approaches that look simpler and fail

Approach Why it fails when the file is larger than memory
Sort through a memory-mapped file with quicksort The partition’s access pattern is not sequential. The device spends the time seeking, and the in-memory n log n formula no longer describes the cost.
A 2-way merge when k streams fit The result is correct and the pass count is log₂ R instead of log_k R. Each extra pass reads and writes the whole file.
Assume every run has length 2M That length is an expectation under replacement selection on random data. The planner should count the runs actually written.
Merge without a heap, rescanning all k heads naively and ignoring I/O CPU time is minor next to a pass. The failure that matters is an extra pass, not the log k inside the heap.

In-memory sorting belongs to whichever comparison or radix sort fits the keys. External mergesort calls that algorithm only inside the run-formation buffer.


A working example

This Python fragment sorts memory-sized runs, writes them as the stand-in for external runs, and merges the run heads with a heap. Eight keys with a run length of 3 come back as 1 2 3 4 5 6 7 8.

import heapq
data = [5, 1, 4, 2, 8, 3, 7, 6]
run_length = 3
runs = [sorted(data[i:i + run_length]) for i in range(0, len(data), run_length)]
heads = [(run[0], r, 0) for r, run in enumerate(runs)]
heapq.heapify(heads)
merged = []
while heads:
    value, r, i = heapq.heappop(heads)
    merged.append(value)
    if i + 1 < len(runs[r]):
        heapq.heappush(heads, (runs[r][i + 1], r, i + 1))
assert merged == sorted(data)
print(*merged)

Where it is used

External mergesort is how a database sorts an ORDER BY that does not fit in memory, and how GNU sort handles a large file. Sorted runs are written out and merged. An in-memory timsort is what builds one run, not what merges the runs.


When you can drop this algorithm

Drop external mergesort when the file fits in memory with room for the sort’s own buffer. An in-memory sort then finishes with no extra pass. Keep it when N is larger than M, and spend the memory on longer runs and a wider k before spending it on a fancier in-memory sort.


Why this stays published

We publish this so a search for external mergesort returns the pass count log_k of the number of runs, and the 2M runs from replacement selection. External mergesort sorts memory-sized runs and merges them k at a time, so the I/O cost is a logarithmic number of sequential passes over the file.

本文由 HoHo 與 AI 協作整理,最後更新於 2026 年 11 月 13 日。

Leave a Reply

Your email address will not be published. Required fields are marked *