Lesson 6: Merge Sort and Quick Sort
The simple sorts compare neighbours and move one step at a time, which is why they are quadratic. The fast sorts use divide and conquer: split the problem into smaller pieces, solve each piece, and combine the answers. Merge sort splits the list in half again and again until each piece has one item — trivially sorted — and then merges the sorted halves back together, always taking the smaller front item first. Merging two sorted lists of total size n costs O(n), and there are log n levels of splitting, so the total is O(n log n) — a huge improvement over O(n^2) for large inputs.
Quick sort takes the same idea in a different direction. It picks a pivot value, partitions the list into items smaller than the pivot and items larger than it, and then sorts each side the same way. On average it is also O(n log n), and it sorts in place, which is why it is the default in many languages. Its weakness is the pivot: if you always pick the first item and the input is already sorted, every partition is lopsided and quick sort degrades to O(n^2). Choosing the pivot well — for example, picking a random item — makes that worst case very unlikely.
def merge_sort(items):
if len(items) <= 1:
return list(items)
mid = len(items) // 2
left = merge_sort(items[:mid])
right = merge_sort(items[mid:])
merged, i, j = [], 0, 0
while i < len(left) and j < len(right):
if left[i] <= right[j]:
merged.append(left[i])
i += 1
else:
merged.append(right[j])
j += 1
return merged + left[i:] + right[j:]
print(merge_sort([5, 2, 4, 1, 3])) # [1, 2, 3, 4, 5]
What Python actually uses
Python's built-in sorted() does not use merge sort or quick sort. It uses Timsort, a hybrid algorithm that looks for runs of already-sorted data in the input and merges them — which is why sorted() is spectacularly fast on real-world data, which is often partly sorted. Timsort is stable, worst-case O(n log n), and written in fast compiled code. The practical lesson is clear: in a contest, use sorted() and spend your thinking time on the problem, not on re-implementing a sort. The theoretical lesson is equally clear: divide and conquer is the pattern behind merge sort, quick sort, binary search, and much of the rest of this course.
One more comparison matters. Merge sort needs O(n) extra space for the merged lists, while quick sort sorts in place with O(log n) stack space. Merge sort is stable; quick sort, in its usual in-place form, is not. And merge sort's O(n log n) is guaranteed, while quick sort's is only average-case. There is no single best sort — there is a best sort for each situation — and knowing the trade-offs is exactly the kind of judgement this course is building.
Going further
Quick sort's partition step has more than one correct form, and the choice affects both speed and stability. The Lomuto scheme picks the last item as the pivot and sweeps through the list once, which is easy to write but does poorly when many items are equal to the pivot. The Hoare scheme picks a pivot and moves two pointers toward each other, which handles duplicates better and usually runs faster. In a contest you will rarely implement either — you will use the built-in sort — but knowing that partition schemes exist, and that duplicates are the weak point, helps you understand why a quick sort can behave badly on real data.
Timsort, Python's built-in sort, deserves a closer look because it explains why sorted() is so fast on real data. It scans the input for runs — stretches that are already sorted — and merges those runs together, using insertion sort for the short ones. Data that is already partly sorted, which is extremely common in practice, is therefore sorted almost for free. The design lesson is general: the best algorithms adapt to the input they are given, rather than treating every input as the worst case.
A good exercise is to trace merge sort by hand on a list of eight numbers, drawing the recursion tree: the list splits into two halves, each half splits again, until every piece is a single item, and then the merges rebuild the sorted list level by level. Count the total work at each level — each level processes all eight items once — and count the levels — three, because eight halves three times. That picture, eight items times three levels, is the O(n log n) bound made visible, and once you have drawn it yourself, the formula stops being something to memorise and becomes something you can see.
Key Terms
- Divide and conquer
- Solving a problem by splitting it into smaller pieces, solving each, and combining the answers.
- Merge sort
- Splits the list in half recursively and merges sorted halves; guaranteed O(n log n), stable, O(n) space.
- Quick sort
- Partitions around a pivot and sorts each side; O(n log n) on average, O(n²) worst case, in place.
- Pivot
- The value quick sort partitions around; a bad pivot choice causes the O(n²) worst case.
- Partition
- Rearranging a list so items smaller than the pivot come first and larger items come after.
- Timsort
- Python's built-in sort: a hybrid of merge sort and insertion sort, stable, O(n log n), fast on partly sorted data.
- Recurrence T(n) = 2T(n/2) + O(n)
- The equation for merge sort's work: two halves plus a linear merge, solving to O(n log n).
Discussion Questions
- Why is merging two sorted lists O(n) rather than O(n²)? Walk through the merge step with two small lists.
- Quick sort is O(n²) in the worst case but O(n log n) on average. Why do programmers accept that risk, and how does a random pivot help?
- When would you choose merge sort over quick sort, even though quick sort is often faster in practice?
Practice Questions
- What is the recurrence for merge sort, and what does it solve to?
- Trace merge sort on [3, 1, 2]. What are the two halves after the first split?
- Why can quick sort degrade to O(n²)?
- Is merge sort stable? Is quick sort (in place)?
- Why should you use Python's sorted() in a contest instead of writing your own sort?
Show answers
- T(n) = 2T(n/2) + O(n), which is O(n log n). Two halves of size n/2, plus a linear merge at each level, over log n levels.
- [3] and [1, 2]. The list splits at the middle; each half is then sorted and merged.
- If the pivot is always the smallest or largest item, every partition is lopsided. Picking the first item of an already-sorted list causes exactly this.
- Merge sort is stable; in-place quick sort is not. The merge takes the left item first on ties, preserving order; partitioning can swap equal items.
- It is Timsort: stable, O(n log n), written in fast compiled code. It also handles partly sorted data very well, and saves your time for the actual problem.