What is Merge Sort
Split the array until every piece has one value, then merge those pieces back together. A merge walks two sorted runs and always takes the smaller head. The picture uses at most 6 values so each split and each choice stays visible.
5 2 4 1 3 1 2 3 4 5
Approach
Merge sort cuts the array in half, sorts each half the same way, then merges the two sorted halves. A single value is already sorted, so the splitting stops there.
Every level merges each value once, and there are about log n levels, so the work is n log n. The merge needs a second array of the same length.
Interactive solution
The finished picture is on screen when the page opens. Next and Play start again from the first step.
Complexity
| Piece | Cost | Why |
|---|---|---|
| Time | O(n log n) | Every level merges n values, and the depth is log n. |
| Extra memory | O(n) | The merge writes into a new run. |
Implementation
def merge(left, right):
out, i, j = [], 0, 0
while i < len(left) and j < len(right):
if left[i] <= right[j]:
out.append(left[i]); i += 1
else:
out.append(right[j]); j += 1
return out + left[i:] + right[j:]
def merge_sort(a):
if len(a) <= 1:
return a
mid = len(a) // 2
return merge(merge_sort(a[:mid]), merge_sort(a[mid:]))