31/41
Part 7 of 7 · Follow-upsLearn

What if the data is too big to sort in memory?

Sort it in pieces. Read as much as fits, sort it, and write it to disk as a sorted run. Repeat until the input runs out. Then merge the runs, which only ever needs the front of each one:

Sorting more than fits in memoryInteractive
the input. Too big for memory

heapq.merge(*runs) takes sorted inputs and hands out one sorted stream, holding only the front item of each input. It doesn't pull all the data into memory at once.

import heapq
import itertools
import tempfile


def external_sort(numbers, chunk):
    runs = []
    numbers = iter(numbers)
    while batch := list(itertools.islice(numbers, chunk)):
        batch.sort()
        run = tempfile.TemporaryFile("w+")
        run.writelines(f"{x}\n" for x in batch)
        run.seek(0)
        runs.append(run)
    return heapq.merge(*((int(line) for line in run) for run in runs))

On a million random integers in chunks of 100,000, ten runs, the output came out in order, and the traced memory peaked at 6.92 MiB. sorted() of the same numbers in memory peaked at 34.76 MiB.

Every number is written once and read back once. With more runs than you can keep open, merge them in rounds. The next lesson, on heaps, builds that merge itself.

How do you find the k-th smallest without a full sort?

If the data is sorted, it's a[k - 1]. If not, a full sort is O(n log n), and you don't need it:

  • Quickselect splits the data around a pivot and keeps only the side that holds position k. That's O(n) on average.
  • A heap of size k keeps the k smallest seen so far in one pass. A heap finds its top item at once and adds or removes one in O(log k), so the pass is O(n log k), which wins when k is small.

The next lesson, on heaps, builds both and measures where each wins. Its worked example finds the k-th smallest in a sorted matrix by binary searching the value, the way this lesson's part on the answer searched the rates.