Merge sort
Split the array in half, sort each half recursively, then merge the two sorted halves.
Merge sort is the classic "divide and conquer" algorithm:
Read the full explanation ↓- Time:
O(n log n) - Space:
O(n) - CLRS, section 2.3
- Horowitz–Sahni, chapter 7
- Johnsonbaugh, chapter 7
Eight mixed numbers: three levels of splitting and seven merges.
def merge_sort(a):sort(a, 0, len(a) - 1)return adef sort(a, lo, hi):if lo >= hi:returnmid = (lo + hi) // 2sort(a, lo, mid)sort(a, mid + 1, hi)merge(a, lo, mid, hi)def merge(a, lo, mid, hi):left = a[lo:mid + 1]right = a[mid + 1:hi + 1]i = 0j = 0k = lowhile i < len(left) and j < len(right):if left[i] <= right[j]:a[k] = left[i]i = i + 1else:a[k] = right[j]j = j + 1k = k + 1while i < len(left):a[k] = left[i]i = i + 1k = k + 1while j < len(right):a[k] = right[j]j = j + 1k = k + 1
Start
Recursion tree
Filled orange = running call · Orange outline = still on the stack · Grey = finished
Local variables
Orange = changed in this step
a list
Call stack
- merge_sort()line 1
How the work grows with input size
Average of 12 random graphs per n (fixed seeds). Hollow marker = the input on screen.
- comparisons
- write
- current input (n=8)
Show as a table
| n | comparisons | write |
|---|---|---|
| 4 | 4.8 | 8 |
| 6 | 9.7 | 16 |
| 8 | 15.3 | 24 |
| 10 | 22.2 | 34 |
| 12 | 30.1 | 44 |
| 14 | 37.7 | 54 |
| 16 | 45.3 | 64 |
Explanation
The idea
Merge sort is the classic "divide and conquer" algorithm:
- Divide: split the range
a[lo..hi]in half atmid. - Conquer: sort each half recursively with the same algorithm. A one-item range is already sorted.
- Combine: merge the two sorted halves.
Merging
The two halves are copied into left and right. At each step, one comparison finds the smallest remaining item of
the two sides, and it is written to a[k]. When one side runs out, the rest of the other side is copied without
comparing.
Cost
- The recursion is
log nlevels deep and each level merges the whole array once, so the time isO(n log n)in every case. - Merging needs a helper array, so the extra memory is
O(n). - The number of comparisons depends on the input: for 8 items it is between 12 (already sorted) and 17 (an interleaved input).
Stability
With the test left[i] ≤ right[j], of two equal items the one from the left half is always written first, so equal
items keep their order and the sort is stable.
What to watch in the trace
- The blue band behind the bars is the range
lo..hiof the running call. - The "recursion tree" under the picture shows which subproblem is running and which are finished.
- Use the "every loop round" detail level to see only the splits, and "every operation" to follow a merge comparison by comparison.