Merge sort in Python, visualized step by step
PythonC
Split the list in the middle, sort each half (with merge sort again), then merge the two sorted halves into one. A list of one value is already sorted, so the splitting stops there.
merge_sort.py
def merge_sort(a):
if len(a) <= 1:
return a
mid = len(a) // 2
left = merge_sort(a[:mid])
right = merge_sort(a[mid:])
merged = []
i = j = 0
while i < len(left) and j < len(right):
if left[i] <= right[j]:
merged.append(left[i])
i += 1
else:
merged.append(right[j])
j += 1
merged += left[i:] + right[j:]
return merged
print(merge_sort([6, 3, 8, 1, 5, 2]))
How Merge sort works
- Length 1 or less: already sorted, return it.
- Split in the middle and sort each half recursively.
- Two pointers start at the heads of the halves; take the smaller value each time.
- When one half runs out, append what is left of the other.
What to watch
The call stackOne level deeper per call: down to the bottom first, then merging back up.
i and jWhile merging, the two pointers take turns: whichever value is smaller goes next.
FAQ
What is the time complexity of merge sort?
O(n log n) in the best, worst and average case: there are log n levels of splitting, and the merges on each level handle n values in total.
Is merge sort stable?
Yes. On a tie the merge takes the left value first (<=), so equal values keep their order.
What is the downside of merge sort?
It needs O(n) extra space for the merged result. Quick sort sorts in place, which often makes it faster in practice.