/utils

Merge Sort

Split the array in halves, sort each half, then merge the two sorted runs. Always O(n log n) and stable, at the cost of a buffer.

SolvesSorting

best
O(n log n)
average
O(n log n)
worst
O(n log n)
space
O(n)

Two sorted lists are easy to combine: look at both fronts and take the smaller value. Merge sort uses this idea. It cuts the array in halves until single values are left, then merges back up.

Already sorted: in every merge the whole left run is smaller, so each merge makes only as many comparisons as the left run is long. That is (n/2) log₂ n in total.

1021324354657687

left = none

1def merge(a, lo, mid, hi):2    left = a[lo:mid]3    i = 04    j = mid5    k = lo6    while i < len(left) and j < hi:7        if left[i] <= a[j]:8            a[k] = left[i]9            i = i + 110        else:11            a[k] = a[j]12            j = j + 113        k = k + 114    while i < len(left):15        a[k] = left[i]16        i = i + 117        k = k + 118 19 20def sort_range(a, lo, hi):21    if hi - lo <= 1:22        return23    mid = (lo + hi) // 224    sort_range(a, lo, mid)25    sort_range(a, mid, hi)26    merge(a, lo, mid, hi)27 28 29def merge_sort(a):30    sort_range(a, 0, len(a))31    return a
1 / 61

a[0..8) has 8 values: split it.

comparisons
0
writes
0

How it works

A run of one value is sorted. Merging two sorted runs gives a longer sorted run [1].

  1. Split a[lo..hi) at mid.
  2. Sort a[lo..mid) and a[mid..hi).
  3. Merge them. Copy the left run to a buffer. Then repeatedly write the smaller front value back into a. When the left run is used up, the rest of the right run is already in place.

Take the left value when both fronts are equal. This keeps the sort stable.

Complexity

CaseInputComparisonsTime
Bestsortedn2log⁡2n\frac{n}{2}\log_2 nO(nlog⁡n)O(n \log n)
Averagerandomabout nlog⁡2nn \log_2 nO(nlog⁡n)O(n \log n)
Worstinterleaving runsnlog⁡2n−n+1n \log_2 n - n + 1O(nlog⁡n)O(n \log n)

There are log⁡2n\log_2 n levels of merging, and each level touches all nn values once. The buffer holds up to n/2n/2 values, so the extra space is O(n)O(n).

Implementations

  • Top-down: the recursive form. The call tree is as deep as log⁡2n\log_2 n.
  • Bottom-up: merges runs of width 1, 2, 4, … in a loop. It does the same merges when nn is a power of two, and needs no stack.

Pitfalls

  • Compute mid as lo + (hi - lo) // 2 in languages with fixed-width integers. (lo + hi) // 2 can overflow.
  • Use <= when comparing the fronts. With < equal values from the right run jump ahead and the sort loses stability.
  • Allocating a new buffer in every merge is slow. Allocate one buffer once and reuse it.

Related

References

  1. T. H. Cormen et al., Introduction to Algorithms, 3rd ed., MIT Press, 2009.

Further reading

  • K. Mehlhorn and P. Sanders, Algorithms and Data Structures: The Basic Toolbox, Springer, 2008.

Full bibliography