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.

6 min readUpdated 2026-11-30
In This Lesson
  • 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).

AlgorithmBest TimeAverage TimeWorst TimeExtra SpaceStable?
Merge SortO(n log n)O(n log n)O(n log n)O(n)Yes
Quick SortO(n log n)O(n log n)O(n²) (sorted + bad pivot)O(log n) stackUsually No
Python TimsortO(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]):

  1. Divide: [38, 27, 43, 3] → [38, 27] and [43, 3] → [38], [27], [43], [3].
  2. Merge bottom-up:
    • merge([38], [27]) → compares 38 <= 27 (False) → [27, 38]
    • merge([43], [3]) → compares 43 <= 3 (False) → [3, 43]
    • merge([27, 38], [3, 43]):
i (left[i])j (right[j])Comparison (left[i] <= right[j])Appendedout 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(), writing if left[i] <= right[j]: picks from left first 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 key key=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-case O(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 arr handles both immediately.
  • All duplicate elements [5, 5, 5, 5]: Naive 2-way Quick Sort degrades to O(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 in O(n)!
Confusing list.sort() vs sorted(list)

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.

Custom Sorting Without Old cmp Functions: Tuple Keys

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?

ScenarioBest ChoiceWhy
Everyday Python sorting / multi-key rankingsorted(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 spaceMerge SortNo random indexing needed; merging pointers is O(1) space
Count inversions (i < j with arr[i] > arr[j])Merge SortCount len(left) - i whenever right[j] < left[i]
K-th smallest/largest without full sortQuickselect or heapqO(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:

Python 3Try It Live: Merge Sort, 3-Way Quick Sort & Timsort
Output

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

Check Your Understanding

What does it mean for a sorting algorithm like Python's Timsort or Merge Sort to be 'stable'?

Check Your Understanding

How can you sort students by highest score first, breaking ties alphabetically by name?

Check Your Understanding

What is the time complexity of Python's Timsort when given an array that is already completely sorted?