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.
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 aa[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].
- Split
a[lo..hi)atmid. - Sort
a[lo..mid)anda[mid..hi). - 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
| Case | Input | Comparisons | Time |
|---|---|---|---|
| Best | sorted | ||
| Average | random | about | |
| Worst | interleaving runs |
There are levels of merging, and each level touches all values once. The buffer holds up to values, so the extra space is .
Implementations
- Top-down: the recursive form. The call tree is as deep as .
- Bottom-up: merges runs of width 1, 2, 4, … in a loop. It does the same merges when is a power of two, and needs no stack.
Pitfalls
- Compute
midaslo + (hi - lo) // 2in languages with fixed-width integers.(lo + hi) // 2can 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
- 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.