Merge sort
Faster sorts · Article 4 of 8 · 4 min read
Split the list, sort each half, then merge: your first divide and conquer algorithm.
The short version
Merge sort splits a list in half, sorts each half the same way, then merges the two sorted halves into one.
Details
Halving takes about log n levels and each level merges n items, so the total is n log n whatever the input. Merging needs extra space for the result.
Try it yourself
def merge_sort(items):
if len(items) <= 1:
return items
middle = len(items) // 2
left = merge_sort(items[:middle])
right = merge_sort(items[middle:])
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
return merged + left[i:] + right[j:]
print(merge_sort([5, 2, 9, 1]))
You should see [1, 2, 5, 9].
Explain it to the duck
Why does using <= instead of < when merging keep the sort stable?
Tested with: Python 3.13.