Loading...
Merge sort divides a sequence into smaller parts and then combines sorted results. The merge step, rather than merely splitting the input, is what establishes the final order.
What you'll be able to do
A sequence of zero or one item is already sorted. Split a larger sequence into two parts, sort each recursively and merge their results. The split need not produce equal sizes when the length is odd, but each recursive part must become smaller.
Draw the split tree and then work back upwards. The order in which recursive calls execute is different from the order in which values appear in the final answer. Splitting into single items does not itself tell the program how to combine them.
Maintain a position in each input. Compare the next unused values and append the smaller to the result, advancing only that input’s position. When one input is exhausted, append the other input’s remaining suffix. The sorted-input assumption justifies each choice.
A stable merge chooses the left item first on equality when the left sequence represents earlier original items. Forgetting to advance a pointer can create a loop; advancing both loses a value. Check that the merged output contains each original item exactly once, including duplicates.
At a given recursion level, merging across all subproblems processes a total proportional to n items. A roughly halving split creates O(log n) levels, producing O(n log n) time for the usual array merge sort. This is more scalable than quadratic sorting for large n.
A common array implementation uses O(n) additional merge storage plus a logarithmic call stack; slicing and allocation can affect practical overhead. Implementations for linked structures or specialised in-place variants differ, so attach storage claims to the version being discussed.
def merge(left, right):
result = []
i = j = 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([2, 7], [1, 6]))Scroll horizontally to see the full code or table.Attempt the task before opening its worked response. Record each change of state, explain the rule used, and check the result against the original requirements. Code examples labelled Python 3 use that language’s conventions; pseudocode states its own assumptions.
Common mistakes to avoid
Key takeaways
Test yourself
Answer a few questions, then review anything you missed.
Start with the quiz above to check the key ideas. You can also choose another topic from the practice library.