
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.
- Divide: split the list in half.
- Conquer: merge-sort each half (a list of 0 or 1 items is already sorted: that's the base case).
- 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().
merge(left, right): both lists are sorted. Return one sorted list with all their items. When two items are equal, take the one fromleftfirst (use<=). This keeps the sort stable.merge_sort(items): return a new sorted list. Lists of length 0 or 1 are returned as a copy; otherwise split atlen(items) // 2, sort each half, andmergethem.
Don't use sorted() or .sort().
merge(left, right): both lists are sorted. Return one sorted list with all their items. When two items are equal, take the one fromleftfirst (use<=). This keeps the sort stable.merge_sort(items): return a new sorted list. Lists of length 0 or 1 are returned as a copy; otherwise split atlen(items) // 2, sort each half, andmergethem.
main.py Python sleeping
Press Run to try your code, then Check to test it.