Vibe Engines
YouTube

Vibe Engines is free, interactive AI engineering & system design — runs in your browser. Pick a learning path

Algorithms · Sorting

Bigger Than Memory.

Watch the explainer

What if the array won’t fit in RAM? You can’t just call sort(). External merge sort handles it in two phases. First, read the data in chunks small enough to fit in memory, sort each chunk, and write it back to disk as a sorted run. Second, k-way merge all the runs at once: keep a pointer into each, and repeatedly emit the smallest value among the current heads. Only a tiny window of each run is ever in memory. Run both phases and watch a dataset far larger than the buffer come out fully sorted.

O(n log n) comparisons · O(n/B) disk I/O · memory holds only one block per run
run

A chunk of data that was small enough to sort in memory, written back sorted.

memory buffer

The limited RAM — holds one chunk to sort, then one block of each run to merge.

k-way merge

Merge all runs at once by repeatedly taking the smallest current head.

streaming

Output is produced incrementally; the full data is never all in memory at once.

extsort.js — make runs, then merge them
Ready
12 numbers, but memory holds only 4 at a time. Phase 1: load 4, sort them in memory, write a sorted run to disk — repeat. Step to begin.
runs
phase
0
runs
0
sorted out

How it works

The insight is that merging is streaming-friendly: to produce the next smallest element of a merged output, you only need to see the current front of each sorted run — not the whole run. So during the merge phase, memory holds just one block from each of the k runs at a time, no matter how large the runs are. That’s why external merge sort scales to data far bigger than RAM while keeping disk I/O sequential (a few passes over the data) rather than random.

1

Phase 1 — make sorted runs

Read as much data as fits in memory, sort it there with a normal in-memory sort, and write it back to disk as a sorted run. Repeat until all input is consumed into runs.

2

Phase 2 — open all runs

Put a read pointer at the start of each sorted run. Only the current head of each run needs to be in memory — one block per run.

3

Emit the smallest head

Compare the heads of all runs, emit the smallest to the output, and advance that run’s pointer. A min-heap makes picking the smallest of k heads efficient.

✓

Repeat until all runs drain

Keep emitting the smallest head until every run is exhausted. The output is fully sorted, and memory never held more than one block per run at a time.

Comparisons
O(n log n)
Disk I/O
sequential
Memory
one block / run
Used in
databases, ETL

The code

# Phase 1: create sorted runs that fit in memory runs = [] while chunk := read(input, MEMORY_SIZE): runs.append(write_run(sorted(chunk))) # sort in RAM, spill to disk # Phase 2: k-way merge with a min-heap of run heads heap = [(peek(r), r) for r in runs]; heapify(heap) while heap: val, r = heappop(heap) emit(val) # smallest current head nxt = advance(r) if nxt is not None: heappush(heap, (nxt, r))

Quick check

1. Why does external merge sort split into runs first?

2. During the merge phase, how much of each run must be in memory?

3. What keeps disk I/O efficient in external merge sort?

FAQ

What is external merge sort?

A sort for data too large for memory. Phase one reads memory-sized chunks, sorts each, and writes sorted runs; phase two k-way merges the runs, keeping only each run’s current head in memory. It sorts arbitrarily large data with bounded memory and sequential disk I/O.

What is a k-way merge?

Merging k already-sorted lists into one at once: keep a pointer into each and repeatedly emit the smallest among the current heads, using a min-heap to find it in O(log k) per element. It generalizes the two-way merge in ordinary merge sort.

How much memory does external merge sort need?

Enough to sort one chunk in phase one, and in phase two one block per run plus an output buffer. More memory means larger runs and a higher merge fan-in, reducing passes over the data. The number of passes is classically expressed in terms of memory M and block size B.

Where is external merge sort used?

Databases (sorting query results, building indexes beyond memory), big-data frameworks (the shuffle/sort in MapReduce, Spark, Hadoop), and tools like the Unix sort utility on files larger than RAM — the standard approach whenever the data exceeds memory.

The picture: three runs, one merge

run 02479run 11358run 2061011k-way mergemin of 3 headsfirst emit: 0from run 20 1 2 3 4 5 6 7 8 9 10 11output, streamed: 12 reads and 12 writes in the merge pass
The page’s 12 numbers with room for 4 in memory. Phase 1 turned them into the three sorted runs above. Phase 2 never loads a run whole: it holds one head per run (the highlighted cell is the smallest head, 0) and writes each winner straight to the output.

Worked example, step by step

Input [7, 2, 9, 4, 1, 8, 5, 3, 6, 0, 11, 10], memory for 4 records, and a block size of one record so that each “I/O” below is one record moved. The merge keeps a min-heap of (value, run) pairs. The counts come from a model that does exactly this.

StepMemoryWhat happenedI/O so far / output
run 0read [7, 2, 9, 4]sort in memory, write [2, 4, 7, 9]4 reads, 4 writes
run 1read [1, 8, 5, 3]sort in memory, write [1, 3, 5, 8]4 reads, 4 writes
run 2read [6, 0, 11, 10]sort in memory, write [0, 6, 10, 11]4 reads, 4 writes
emit #1heads now [2, 1, 6]smallest head was 0 (run 2)output [0]
emit #2heads now [2, 3, 6]smallest head was 1 (run 1)output [0, 1]
emit #3heads now [4, 3, 6]smallest head was 2 (run 0)output [0, 1, 2]
emit #4heads now [4, 5, 6]smallest head was 3 (run 1)output [0, 1, 2, 3]
emit #5heads now [7, 5, 6]smallest head was 4 (run 0)output [0, 1, 2, 3, 4]
emit #12heads now ['done', 'done', 'done']smallest head was 11 (run 2)output complete, 12 writes

Phase 1 read each record once and wrote it once: 12 reads, 12 writes, three runs. Phase 2 does the same again, so the whole sort costs 48 record I/Os, which is 2 passes over the data. The trace shows why the memory bound holds: at every emit only three heads and one output slot are resident, 4 records, however long the runs are. It also shows the merge is not sorting anything. It only ever compares three numbers, and the numbers it skipped are guaranteed bigger because each run is already in order. Every record is read twice and written twice, once per phase; adding passes multiplies that, which is the central cost to manage.

Complexity and trade-offs

CaseTimeSpaceWhy
k-way merge, fan-in k = M/B − 1O((N/B)·(1 + logk(N/M))) block I/Os; O(N log N) comparisonsO(M) memoryEach pass reads and writes every block once. Raising the fan-in cuts the number of passes. 1,000 records, memory 10, block 1: fan-in 9 needs 4 passes.
Two-way merge passesO((N/B)·log2(N/M))O(B) memory per runSame code with k = 2. The same 1,000 records and memory of 10 need 8 passes, twice the I/O.
Run formation by replacement selectionone pass, O(N log M)O(M)Keeps a heap and streams records through it. On 100,000 random values with M = 100 it produced 500 runs, average length 200, against 1,000 runs of exactly 100.
Sort in memoryO(N log N)O(N)Fastest when the data fits, impossible when it does not. External sort is the fallback, not the first choice.

The number to watch is passes, because I/O is passes × data size. It depends on the ratio N/M and the fan-in, and grows only logarithmically: 12 records at memory 4 take 2 passes, 16 records at memory 4 take 3, and a million records with memory for a thousand take 3 when the fan-in is 999 but 11 when it is 2. The usual tuning is therefore to give the merge as many input buffers as memory allows, and to make runs as long as possible.

Common mistakes

  • Forgetting the output buffer

    Merging k runs needs k input slots plus one output slot. With memory for 4 records the largest fan-in is 3, not 4. A fan-in of 4 would hold 5 records at once. On 16 records with memory 4 the correct plan is 4 runs, merged 3 at a time: 3 passes in total.

  • Loading each run whole during the merge

    This undoes the point of the algorithm. On the page’s 12 records it keeps all 12 in memory, three times the budget of 4. Stream each run and keep only its head (and a block of read-ahead, in a real system).

  • Breaking ties with the record instead of the run

    If the heap compares whole records, equal keys are ordered by their payload. Two records with key 1 and payloads "z" then "a" come out as a, z, reversing their original order. Use (key, run_index) so equal keys keep their input order, given that runs themselves were produced by a stable sort.

  • Making runs smaller than memory

    Sorting one record at a time “because it is simpler” yields 12 runs from 12 records. At fan-in 3 that is 4 passes instead of 2, and 96 record I/Os instead of 48. Fill memory every time; replacement selection can even double the run length.

  • Counting only comparisons

    Comparisons are O(N log N) in every variant above. The cost that differs is I/O. Judging two plans by comparisons alone cannot tell the 2-pass plan from the 4-pass one.

Where this shows up

  • Database sorts and joins

    An ORDER BY or a sort-merge join on a table larger than the work memory spills sorted runs to temporary files and merges them. The planner chooses it on a cost model built from exactly the pass count above.

  • Sorting a file bigger than RAM

    Command-line sort utilities split large input into sorted temporary files and merge them. The same two phases appear in log processing and ETL jobs.

  • Distributed sorting

    A cluster sort sorts each partition locally, then merges sorted streams, with workers in place of runs. Memory per worker plays the role of M.

  • LSM compaction

    Merging sorted files while dropping stale versions is the same k-way merge, with an extra rule for duplicates. Learning one pays for the other.

SOLVE IT YOURSELF

Solve it: sort more data than fits in RAM

You have a billion records and memory for a million. Sorting in place is impossible — but sorting chunks is easy, and merging sorted chunks needs only one record from each in memory at a time. That is the whole trick. Python or TypeScript.

YOUR TASK

Implement make_runs(data, mem) (makeRuns) and merge_runs(runs) (mergeRuns), plus external_sort tying them together. Track PEAK: the most records held in memory at once during the merge.

HINTS — 7 IDEAS
  1. Phase 1: read exactly mem records, sort them in memory, write the sorted block out as a "run". Repeat until the input is consumed. Peak memory is one block, whatever the input size.
  2. Phase 2: open every run at once and repeatedly emit the smallest current head. Only one record per run is ever in memory — that is why the merge is nearly free on memory.
  3. A linear scan over the heads costs O(k) per record. A min-heap of heads costs O(log k), which is what matters once k is large.
  4. Push a run's next record only after popping its current head. Pushing eagerly would defeat the point and pull whole runs into memory.
  5. A run that drains simply stops contributing — no special case needed, since it is only absent from the heap.
  6. Peak merge memory is k, the run count — not the data size. That is what makes this work for a billion records.
  7. Real systems add a second layer: when k exceeds the file-handle budget, merge in passes rather than all at once.
CPython · WebAssembly

Keep going

▶  Watch it explained

External Merge Sort: Time and Space Complexity, From First Principles

Finished this one? 0 / 99 Algorithms done

Explore the topic

See this alongside everything else on the same subject — handbooks, system designs, challenges and tools, in one place.

More Algorithms