Merge sort

Split the array in half, sort each half, then merge them: a guaranteed O(n log n), stable sort, and the basis for sorting data too big for memory.

Description

Merge sort is the textbook divide-and-conquer algorithm. Split the array into two halves, sort each half recursively, then merge them: repeatedly take the smaller front value of the two sorted halves until both are empty.

Merging two sorted lists of total length n takes n steps, and halving gives log₂ n levels, so merge sort is O(n log n) in every case: best, average and worst. It's also stable, because when two front values are equal it takes from the left half first.

The cost is memory: a standard array merge sort needs O(n) extra space for merging. Linked lists can be merge-sorted without extra arrays.

Because merging reads both inputs sequentially, merge sort is the basis of external sorting: sorting files too large for memory by sorting chunks and merging them from disk. Databases use it for big ORDER BY queries, and Timsort, the default sort in Python and for objects in Java, is a refined merge sort.

How it works

10014129237354135226417leftright

Two sorted halves about to be merged

  1. index 0: 10
  2. index 1: 14
  3. index 2: 29
  4. index 3: 37
  5. index 4: 5
  6. index 5: 13
  7. index 6: 22
  8. index 7: 41
Two sorted halves about to be merged

Step through: merge sort (each step writes one value)

291014371354122

Step 1 of 25Start with 8 values.

0 comparisons, 0 writes
New data: , , ,

Complexity

OperationAverageWorst
Sort (any input)O(n log n)O(n log n)
Merge two sorted listsO(n)O(n)

Space: O(n) for arrays; O(log n) for linked lists

Merge sort does fewer comparisons than quicksort but more data movement, and its extra memory usually makes it a little slower for in-memory arrays of numbers.

TypeScript implementation

Top-down merge sort with a single reused buffer, and a check that it keeps equal keys in their original order.

merge-sort.ts
// Top-down merge sort with one reusable buffer. Stable: ties take from the left.

export function mergeSort<T>(a: T[], compare: (x: T, y: T) => number): T[] {
  const buf = a.slice();
  const sort = (lo: number, hi: number) => {
    if (hi - lo < 2) return;
    const mid = (lo + hi) >> 1;
    sort(lo, mid);
    sort(mid, hi);
    let i = lo, j = mid, k = lo;
    while (i < mid && j < hi) buf[k++] = compare(a[j], a[i]) < 0 ? a[j++] : a[i++]; // `<` keeps ties stable
    while (i < mid) buf[k++] = a[i++];
    while (j < hi) buf[k++] = a[j++];
    for (k = lo; k < hi; k++) a[k] = buf[k];
  };
  sort(0, a.length);
  return a;
}

export function demo(): string[] {
  const nums = mergeSort([29, 10, 14, 37, 13, 5, 41, 22], (x, y) => x - y);
  // Stability: orders already sorted by time, now sorted by customer, keep their time order.
  const orders = [
    { customer: "lee", time: "09:00" }, { customer: "kim", time: "09:05" },
    { customer: "lee", time: "09:10" }, { customer: "kim", time: "09:20" },
  ];
  const byCustomer = mergeSort(orders, (x, y) => x.customer.localeCompare(y.customer));
  return [
    `[${nums.join(", ")}]`,
    `stable by customer: ${byCustomer.map((o) => `${o.customer} ${o.time}`).join(", ")}`,
  ];
}

When to use it

Use it when

  • You need a stable sort with guaranteed O(n log n).
  • Sorting linked lists, or data on disk or in streams.
  • Merging already-sorted inputs, such as results from several servers.

Avoid it when

  • Memory is tight and you can't afford O(n) extra: use heapsort or an in-place quicksort.
  • You just need to sort in your language: the built-in sort is already a tuned merge sort or similar.

Pitfalls

  • Allocating new arrays at every level, which is slow. Allocate one buffer and reuse it.
  • Taking from the right on ties, which breaks stability.
  • Recursing down to single elements: switching to insertion sort for small pieces is noticeably faster.

Alternatives

Quicksort

Choose it when you sort arrays in memory, don't need stability, and want the fastest average case.

Timsort

Choose it when data has existing order you want to exploit; it's merge sort plus run detection.

Heapsort

Choose it when you need O(n log n) worst case with O(1) extra memory.