Merge Sorted Runs with Merge Sort
Core idea
Merge sort splits a list until sublists have at most one item, sorts each half recursively, then merges them. At each merge step choose the smaller front value; choose the left one on a tie for stability. This list-based version uses O(n log n) time and O(n) peak auxiliary space (including temporary lists, with recursion depth O(log n)).
def merge(a, b): i = j = 0 out = [] while i < len(a) and j < len(b): if a[i] <= b[j]: out.append(a[i]); i += 1 else: out.append(b[j]); j += 1 return out + a[i:] + b[j:]print(merge([1, 4, 4], [2, 5]))After either run ends, append the remaining suffix.
Split and combine
from heapq import mergedef mergesort(a): if len(a) <= 1: return a[:] mid = len(a)//2 return list(merge(mergesort(a[:mid]), mergesort(a[mid:])))print(mergesort([7, 1, 3, 1]))print(mergesort([]))heapq.merge lazily merges sorted inputs; list collects the result. The base case covers empty input.
Common mistake
Do not use pop(0) repeatedly on lists in a linear merge; shifting the remaining items adds unnecessary work.
Practice
Implement merge sort using the first merge function instead of heapq.merge; test duplicates and empty halves.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Merge sort
Check your understanding of merge sort.
What is printed?
from heapq import mergeprint(list(merge([2,6],[1,4])))What is printed?
from heapq import mergeprint(list(merge([], [3,3])))Which side should win ties in a stable merge?
Time for balanced merge sort?