Merge sort
medium 18 minMerge sort splits the array in half until every piece holds one value, then merges sorted pieces back together with two pointers.
See it run
Split the array in half until every piece is one value, then merge sorted pieces back together with two pointers.
Operations
Split and merge
The recursion tree of [38, 27, 43, 3, 9, 82, 10], walked in the order the calls really run: all the way down the left side first, merging on the way back up.
Step 1 of 12
Seven values, one call
merge_sort(a, 0, 6) is called on the whole array [38, 27, 43, 3, 9, 82, 10]. Faded boxes are calls that have not happened yet; the tree shows what each call will hold.
Step 1: Seven values, one call
def merge_sort(a, lo, hi): if lo >= hi: # 0 or 1 value: already sorted return mid = (lo + hi) // 2 # divide merge_sort(a, lo, mid) # conquer the left half merge_sort(a, mid + 1, hi) # conquer the right half merge(a, lo, mid, hi) # combinedef merge(a, lo, mid, hi): left, right = a[lo:mid + 1], a[mid + 1:hi + 1] i = j = 0 k = lo while i < len(left) and j < len(right): if left[i] <= right[j]: # ties go left: stable a[k] = left[i]; i += 1 else: a[k] = right[j]; j += 1 k += 1 while i < len(left): # copy leftovers a[k] = left[i]; i += 1; k += 1 while j < len(right): a[k] = right[j]; j += 1; k += 1nums = [38, 27, 43, 3, 9, 82, 10]merge_sort(nums, 0, len(nums) - 1)print(nums) # [3, 9, 10, 27, 38, 43, 82]- Time
- O(n log n) always
- Space
- O(n)
- this run
- 6 merges, 14 comparisons
- levels
- ⌈log₂ 7⌉ = 3
All the comparing happens on the way back up. Splitting is free; merging is where the n log n comes from.
In the real world
The same merge sort doing real jobs. Pick one and step through it.
A teacher sorts four exam papers by score with two assistants: split the stack, sort the small piles, merge by always taking the lower top score.
Step 1 of 5
A messy stack
The teacher holds four papers scored 72, 45, 90, 61, in no order. Sorting them alone feels like work, so the teacher gets help.
Step 1: A messy stack
import heapqpile_a = sorted([72, 45]) # assistant 1: [45, 72]pile_b = sorted([90, 61]) # assistant 2: [61, 90]print(list(heapq.merge(pile_a, pile_b))) # [45, 61, 72, 90]Common mistakes
The bugs interviewers watch for, with the fix beside each.
Base case that misses length 1
criticalA list of one value splits into [] and itself. The second call is just as big as the first, so the recursion never ends and Python raises RecursionError.
Wrongdef merge_sort(arr): if len(arr) == 0: return arr mid = len(arr) // 2 # len 1: mid = 0, right half is the whole listRightdef merge_sort(arr): if len(arr) <= 1: # 0 or 1 values: already sorted return arr mid = len(arr) // 2Splitting so a range never shrinks
criticalWith mid = (lo + hi) // 2, the halves must be [lo, mid] and [mid + 1, hi]. Using [lo, mid - 1] and [mid, hi] means a two-value range (lo, lo + 1) recurses on itself forever.
Wrongmid = (lo + hi) // 2merge_sort(a, lo, mid - 1)merge_sort(a, mid, hi) # lo=0, hi=1: mid=0, calls (0, 1) againRightmid = (lo + hi) // 2merge_sort(a, lo, mid)merge_sort(a, mid + 1, hi)Forgetting the leftovers
criticalThe main loop stops as soon as one run is empty. Whatever is still in the other run must be copied, or those values vanish from the output.
Wrongwhile i < len(left) and j < len(right): ...return result # values left in one run are lostRightwhile i < len(left) and j < len(right): ...result.extend(left[i:])result.extend(right[j:])return resultUsing < in the merge
majorOn a tie, < takes the right run's value first, so equal values swap their original order. The output is still sorted, but the sort is no longer stable, which breaks sorting records by several keys.
Wrongif left[i] < right[j]: # ties go right: unstable result.append(left[i])Rightif left[i] <= right[j]: # ties go left: stable result.append(left[i])Merging in place without copying the runs
criticalWriting a[k] while still reading from a[lo..hi] overwrites values that have not been merged yet. Copy the two runs out first, or merge into a separate buffer.
Wrongi, j, k = lo, mid + 1, lowhile i <= mid and j <= hi: if a[i] <= a[j]: a[k] = a[i]; i += 1 else: a[k] = a[j]; j += 1 # overwrites a[k], which may be an unread left value k += 1Rightleft, right = a[lo:mid + 1], a[mid + 1:hi + 1]i = j = 0k = lowhile i < len(left) and j < len(right): ...pop(0) inside the merge
majorlist.pop(0) shifts every remaining element, so it costs O(n). Doing it once per value makes each merge O(n²) and the whole sort far slower than O(n log n). Walk with indexes instead.
Wrongwhile left and right: result.append(left.pop(0) if left[0] <= right[0] else right.pop(0))Rightwhile 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
Interview tips
How to explain it
- Divide at the middle, sort both halves recursively, merge the sorted halves with two pointers.
- log n levels of splitting, n work per level of merging: O(n log n) on every input.
- O(n) extra space for the merge buffers, O(log n) stack. Stable because ties take from the left.
- Recurrence: T(n) = 2T(n/2) + n.
Spot it in the wild
- A stable sort or a guaranteed worst case is required.
- Sorting a linked list, or data too big for memory.
- Counting inversions, or merging k sorted lists or streams.
Memory tricks
- DSCM: Divide, Split, Conquer, Merge.
- Split costs nothing, merge does everything.
- When one pile runs out, dump the other on top.
Watch out
- Base case len <= 1, not len == 0.
- Halves are [lo, mid] and [mid + 1, hi].
- Copy the leftovers, and use <= to stay stable.