Divide. Sort. Recombine..
Merge sorted halves and account for the memory the implementation actually uses.
01 Model 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.
Each merge output is sorted and contains exactly the consumed values.
02 State the strategy
Read the steps independently of syntax. Explain what each step preserves before translating it into code.
SPLIT the sequence into halves
SORT each half recursively
MERGE their smallest front candidates
APPEND any remaining suffix03 Make it concrete
The implementation uses Python 3.11+ with only the standard library. Run it locally, or download the independent DSA workbench.
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]
- 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 Count the cost
O(n log n)
O(n) peak auxiliary plus O(log n) stack
Bounds refer to the shown implementation and exclude printed output unless stated. n is input size; V and E are graph vertices and edges.
05 Your next move
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]))06 Check your reasoning
Why are the two inputs to merge required to be sorted?
Understand it. Then own it.
Can you explain the invariant, trace an edge case, and defend the cost model? Log the experiment when the reasoning makes sense.