Divide. Sort. Recombine..
Merge sorted halves and account for the memory the implementation actually uses.
01 The idea
Merge sort divides an input into smaller parts, sorts those parts, and merges them in order. Merging two sorted sequences takes linear work in their combined length. Across logarithmically many levels, the usual time bound is O(n log n). A Python implementation using slices and new lists also allocates storage; its practical costs include those copies.
02 The experiment
Read it once. Predict what will happen. Then copy it into a .py file and run it in your local Python setup.
def merge_sort(values):
if len(values) <= 1: return list(values)
middle = len(values) // 2
left, right = merge_sort(values[:middle]), merge_sort(values[middle:])
result, i, j = [], 0, 0
while i < len(left) and j < len(right):
if left[i] <= right[j]:
result.append(left[i]); i += 1
else:
result.append(right[j]); j += 1
return result + left[i:] + right[j:]
print(merge_sort([9, 2, 7, 2, 1]))[1, 2, 2, 7, 9]
03 Under the hood
- 1
The base case handles an empty or one-item sequence. Slicing makes each recursive subproblem explicit.
- 2
The merge loop always takes the smaller front item. Taking the left item on equality preserves stability for the comparison used here.
- 3
At most one side still has remaining values after the loop. Appending its suffix completes the result. Prefer sorted() in production unless you have a justified specialist requirement.
04 Your turn, builder
Write a merge function for two already-sorted integer lists.
Reveal one possible solution +
def merge(left, right):
result, i, j = [], 0, 0
while i < len(left) and j < len(right):
if left[i] <= right[j]: result.append(left[i]); i += 1
else: result.append(right[j]); j += 1
return result + left[i:] + right[j:]
print(merge([1, 4], [2, 3, 5]))05 Check your signal
Why are the two inputs to merge required to be sorted?
Experiment. Logged.
When you can explain the idea and make the example your own, mark it complete. Your log stays in this browser.
Keep exploring
Go deeper with the official Python guide ↗.