Algorithms Playbook
ConceptTime O(n log n) · Space O(n)9 min read

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.

Merge sort: split, sort, merge
Speed
051229314753
1def merge_sort(a, lo, hi):
2 if hi - lo <= 1: return
3 mid = (lo + hi) // 2
4 merge_sort(a, lo, mid)
5 merge_sort(a, mid, hi)
6 merged, i, j = [], lo, mid
7 while i < mid and j < hi:
8 if a[i] <= a[j]:
9 merged.append(a[i]); i += 1
10 else:
11 merged.append(a[j]); j += 1
12 merged += a[i:mid] + a[j:hi]
13 a[lo:hi] = merged
Merge sort: split in halves until single elements, then merge sorted halves back together.

Variables

n6
Step 1/48· Comparisons: 0
Each level of splitting does O(n) work merging, and there are log n levels: O(n log n) always, with O(n) extra space.

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 sortQuicksort
Worst caseO(n log n)O(n²)
Extra spaceO(n)O(log n) (the recursion)
StableYesNo
Good forLinked lists, external sortingArrays, 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