AlgoViz

Merge sort

medium 18 min

Merge sort splits the array in half until every piece holds one value, then merges sorted pieces back together with two pointers.

Where it shows up

The same pattern appears across everyday software.

  • Python's sorted() and Java's object sort

    Both use Timsort, a merge sort descendant that finds runs already in order and merges them. It is stable, which is why sorting records by one field keeps earlier orderings intact.

  • Databases sorting more data than fits in memory

    When an ORDER BY or a sort-merge join spills to disk, the engine sorts chunks in memory, writes them as runs and merges the runs: external merge sort.

  • The Unix sort command

    GNU sort sorts huge files by writing sorted temporary files and merging them, so it can sort files many times larger than RAM.

  • MapReduce and big-data shuffles

    Each worker sorts its output locally, and reducers merge the sorted streams from many workers into one ordered stream.

  • Merging sorted logs and feeds

    Combining time-ordered logs from many servers is the merge step on k inputs: always take the earliest front entry.

  • Sorting linked lists

    Library list sorts, such as the Linux kernel's list_sort, use merge sort because merging only relinks nodes and needs no random access.