Merge sort and quicksort: divide and conquer
The two sorts every interviewer expects you to know: how each one splits the work, their costs, and when to pick which.
In short
Both divide and conquer. Merge sort splits in half, sorts each, and merges: always O(n log n), stable, O(n) extra space. Quicksort partitions around a pivot, then sorts each side: O(n log n) on average, O(n²) worst case, in place.
Merge sort: split, sort, merge
A single element is already sorted. Merging two sorted halves is easy: compare the fronts and take the smaller. So split until you hit single elements, then merge back up.
1def merge_sort(a, lo, hi):2 if hi - lo <= 1: return3 mid = (lo + hi) // 24 merge_sort(a, lo, mid)5 merge_sort(a, mid, hi)6 merged, i, j = [], lo, mid7 while i < mid and j < hi:8 if a[i] <= a[j]:9 merged.append(a[i]); i += 110 else:11 merged.append(a[j]); j += 112 merged += a[i:mid] + a[j:hi]13 a[lo:hi] = merged
Variables
There are log n levels of splitting and each level merges n elements in total: O(n log n), whatever the input.
Quicksort: partition around a pivot
def quicksort(a, lo, hi):
if lo >= hi: return
p = partition(a, lo, hi) # pivot lands in its final spot
quicksort(a, lo, p - 1)
quicksort(a, p + 1, hi)- Partition: move everything smaller than the pivot to its left and everything bigger to its right. The pivot is now in its final position.
- Average: a decent pivot halves the problem: O(n log n).
- Worst case: a bad pivot every time (already-sorted input with the first element as pivot) gives O(n²). A random or median-of-three pivot makes it very unlikely.
- Quickselect: the same partition finds the k-th smallest in O(n) on average, without fully sorting.
Which one, and what about the built-in sort?
| Merge sort | Quicksort | |
|---|---|---|
| Worst case | O(n log n) | O(n²) |
| Extra space | O(n) | O(log n) (the recursion) |
| Stable | Yes | No |
| Good for | Linked lists, external sorting | Arrays, in memory |
Key takeaways
- 01Merge sort: always O(n log n), stable, needs O(n) extra space.
- 02Quicksort: O(n log n) on average, O(n²) worst case, sorts in place.
- 03A stable sort keeps equal elements in their original order.
- 04Sorting first often turns a hard problem into a single pass.
Check your understanding
1 of 3
What's merge sort's time complexity in the worst case?
Related topics
Recursion
A recursive function solves a problem by calling itself on a smaller version of it, until it reaches a base case it can answer directly. Each pending call waits on the call stack, so recursion costs memory too.
8 min read →Intervals
Sort by start, then walk once. An interval either overlaps the last one (extend its end with `max`) or starts a new group. Cost: O(n log n) for the sort, O(n) for the sweep.
7 min read →