Code

Merge Sort: Divide & Conquer

Divide & conquer splits a problem into halves, solves each half (recursively), then combines the answers. Binary search was a taste; merge sort is the classic.

  1. Divide: split the list in half.
  2. Conquer: merge-sort each half (a list of 0 or 1 items is already sorted: that's the base case).
  3. Combine: merge the two sorted halves into one sorted list.

Merging two sorted lists is easy: repeatedly take the smaller of the two front items.

[1, 4, 9] + [2, 3]  gives  1, 2, 3, 4, 9

The list is halved about log₂ n times, and each level does O(n) merging work, so merge sort is O(n log n). For a million items that's roughly 20 million steps instead of a trillion for bubble sort!

Assignment

Don't use sorted() or .sort().

  1. merge(left, right): both lists are sorted. Return one sorted list with all their items. When two items are equal, take the one from left first (use <=). This keeps the sort stable.
  2. merge_sort(items): return a new sorted list. Lists of length 0 or 1 are returned as a copy; otherwise split at len(items) // 2, sort each half, and merge them.