3. Recursion, Searching & Sorting
Sorting Algorithms: Merge Sort, Quick Sort & Timsort
Understand divide-and-conquer sorting: implement stable O(n log n) Merge Sort and in-place Quick Sort, and learn why Python's built-in Timsort is fast and stable.
- Implement Merge Sort using divide-and-conquer and explain its guaranteed O(n log n) runtime
- Compare Quick Sort's average O(n log n) vs worst-case O(n²) behavior
- Understand stability and multi-key sorting in Python's built-in Timsort
While you should always use sorted() or list.sort() in production Python, technical interviews frequently test Merge Sort (the backbone of external/linked-list sorting and inversion counting), Quick Sort / Quickselect (K-th largest in O(n) average time), and sorting stability.
Why It Matters: Comparing O(n²) vs O(n log n) Sorts
Simple sorts like Insertion Sort and Bubble Sort compare adjacent elements and take O(n²) worst-case time—100,000 items would require billions of swaps. Divide-and-conquer algorithms split the problem recursively into halves (log₂ n levels), doing O(n) merge or partition work per level → O(n log n).
| Algorithm | Best Time | Average Time | Worst Time | Extra Space | Stable? |
|---|---|---|---|---|---|
| Merge Sort | O(n log n) | O(n log n) | O(n log n) | O(n) | Yes |
| Quick Sort | O(n log n) | O(n log n) | O(n²) (sorted + bad pivot) | O(log n) stack | Usually No |
| Python Timsort | O(n) (already/nearly sorted!) | O(n log n) | O(n log n) | O(n) | Yes |
Pattern 1: Divide-and-Conquer Merge Sort
Mental Model & Step-by-Step Dry-Run Trace
Merge Sort splits the array down to single-element lists (which are trivially sorted!), then zips sorted pairs back together using two pointers i and j:
Trace merge_sort([38, 27, 43, 3]):
- Divide:
[38, 27, 43, 3]→[38, 27]and[43, 3]→[38],[27],[43],[3]. - Merge bottom-up:
merge([38], [27])→ compares38 <= 27(False) →[27, 38]merge([43], [3])→ compares43 <= 3(False) →[3, 43]merge([27, 38], [3, 43]):
i (left[i]) | j (right[j]) | Comparison (left[i] <= right[j]) | Appended | out After Step |
|---|---|---|---|---|
0 (27) | 0 (3) | 27 <= 3 (False) | 3 (j=1) | [3] |
0 (27) | 1 (43) | 27 <= 43 (True) | 27 (i=1) | [3, 27] |
1 (38) | 1 (43) | 38 <= 43 (True) | 38 (i=2) | [3, 27, 38] |
2 (done) | 1 (43) | Loop ends → out.extend(right[1:]) | 43 | [3, 27, 38, 43] |
Why Stability Matters (and How <= Preserves It)
Stability means elements with equal sort keys stay in their original relative order.
- In
merge(), writingif left[i] <= right[j]:picks fromleftfirst on ties, preserving original order! - Because Python's Timsort (
sorted()/.sort()) is guaranteed stable, you can sort by secondary criteria first and primary criteria second—or pass a tuple keykey=lambda x: (-x["score"], x["name"]).
Pattern 2: Quick Sort & Quickselect Partitioning
Quick Sort picks a pivot, partitions elements smaller than pivot to the left and larger to the right, and recurses:
- Randomized pivot: Picking
pivot = nums[random.randint(lo, hi)]makes worst-caseO(n²)astronomically unlikely even on sorted input! - Quickselect bonus: If you only need the K-th largest item, you only recurse into one side of the partition →
O(n)average time!
Edge Cases to Always Check
- Empty list
[]or 1-element list[42]:if len(arr) <= 1: return arrhandles both immediately. - All duplicate elements
[5, 5, 5, 5]: Naive 2-way Quick Sort degrades toO(n²)on all-equal inputs! Use 3-way Dutch National Flag partitioning (< pivot,== pivot,> pivot) or Merge Sort / Timsort. - Already sorted input
[1, 2, 3, 4, 5]: Timsort detects the ascending "run" and finishes inO(n)!
nums.sort() sorts in place and returns None! Writing x = nums.sort() sets x to None and triggers TypeError later. Use sorted(nums) when you need a new sorted list and want to keep nums unchanged.
Python's key= parameter is evaluated once per item (O(n)), then Timsort compares the resulting keys in C. To sort mixed directions (e.g., highest score first, then alphabetical name), return a tuple: key=lambda p: (-p[1], p[0]).
Pattern Recognition: Which Sort Tool for the Job?
| Scenario | Best Choice | Why |
|---|---|---|
| Everyday Python sorting / multi-key ranking | sorted(arr, key=...) (Timsort) | C-speed, stable, O(n) on nearly sorted data |
Sort a Linked List in O(n log n) and O(1) extra space | Merge Sort | No random indexing needed; merging pointers is O(1) space |
Count inversions (i < j with arr[i] > arr[j]) | Merge Sort | Count len(left) - i whenever right[j] < left[i] |
| K-th smallest/largest without full sort | Quickselect or heapq | O(n) average or O(n log k) |
Try It Yourself in the Playground
Implement and test Merge Sort, 3-Way Quick Sort, and Python's multi-key Timsort right below:
Click “Run Code” to execute this snippet right in your browser.
Mini-Challenge: Why is <= (instead of <) used inside merge() when comparing left[i] <= right[j]?
Quick Checkpoints
What does it mean for a sorting algorithm like Python's Timsort or Merge Sort to be 'stable'?
How can you sort students by highest score first, breaking ties alphabetically by name?
What is the time complexity of Python's Timsort when given an array that is already completely sorted?