Skip to content

Lesson 31 of 40Advanced patterns

Sorting

Understand merge sort, quicksort and quickselect, what stability means, and how to sort anything with keys, comparators and buckets.

25 min read0/6 questions

Sorting is the most common preprocessing step in all of programming. Sorted data lets you binary search, find duplicates by looking at neighbours, merge intervals, use two pointers, and show users a tidy list. Many "hard" problems become easy one line after sort().

You will almost never write a sort at work; the built-in one is faster than anything you would write. But interviewers ask how merge sort and quicksort work, because they are the clearest examples of divide and conquer, and you need to know what the built-in sort guarantees (and the one JavaScript default that catches everyone).

The simple sorts: O(n²)

Bubble sort walks the list swapping neighbours that are out of order, repeating until nothing moves. Large values "bubble" to the end. It is mostly of historical interest.

Insertion sort is the one worth knowing. It is how you sort a hand of cards: take the next card and slide it left until it sits in the right place among the cards already sorted.

Python
def insertion_sort(nums): for i in range(1, len(nums)): x = nums[i] j = i - 1 while j >= 0 and nums[j] > x: # shift bigger items right nums[j + 1] = nums[j] j -= 1 nums[j + 1] = x # drop x into the gap return nums print(insertion_sort([5, 2, 4, 6, 1, 3]))
Output
Press Run (⌘ Enter) to see what happens.

Both are O(n²) in the worst case: a reversed list makes every item slide all the way. But insertion sort is O(n) on an almost-sorted list (each item slides only a little) and very fast on tiny lists. That is why real-world sorts use it for small chunks.

Quick check
Insertion sort on a list of 1,000,000 items that is already sorted except for two swapped neighbours. Roughly how much work?
Need a nudge? A hint rules out a wrong answer.

Merge sort: divide and conquer

Divide and conquer means: split the problem into halves, solve each half recursively, and combine the answers. Merge sort applies it directly:

  1. Split the list in half.
  2. Sort each half (recursively; a list of 0 or 1 items is already sorted).
  3. Merge the two sorted halves into one sorted list.
Merge sort splits [5, 2, 4, 6, 1, 3]
[5,2,4,6,1,3][5][2][4][2,4][5,2,4][6][1][3][1,3][6,1,3]root

Start with six items. Split down the middle.

1/6

The merge step is two pointers. Compare the front of each half, take the smaller, advance that pointer. When one half runs out, copy the rest of the other.

Merging [2, 4, 5] and [1, 3, 6]
2
0
↑i
4
1
5
2
1
3
↑j
3
4
6
5
out = []

Left half is indexes 0 to 2, right half 3 to 5. Compare the fronts: 2 vs 1.

1/5

Merge sort is O(n log n) in every case (best, average, worst), because the splits are always even. It needs O(n) extra space for merging. And it is stable, a word we will define shortly, as long as ties take from the left half first (<=, not <).

Python
def merge_sort(nums): if len(nums) <= 1: return nums mid = len(nums) // 2 left, right = merge_sort(nums[:mid]), merge_sort(nums[mid:]) out, i, j = [], 0, 0 while i < len(left) and j < len(right): if left[i] <= right[j]: # <= keeps equal items in order (stable) out.append(left[i]); i += 1 else: out.append(right[j]); j += 1 return out + left[i:] + right[j:] print(merge_sort([5, 2, 4, 6, 1, 3]))
Output
Press Run (⌘ Enter) to see what happens.
ChallengeMedium

Merge sort

Sort a list of integers in ascending order using merge sort. Do not call the built-in sort.

Split the list in half, sort each half recursively, then merge the two sorted halves with two pointers.

[5, 2, 4, 6, 1, 3]  →  [1, 2, 3, 4, 5, 6]
[]                  →  []

Return a new sorted list. Your solution should be O(n log n) time.

def merge_sort(nums: list[int]) -> list[int]: # Base case, split, sort both halves, merge. pass

Quicksort: partition around a pivot

Quicksort divides differently. Pick a pivot value, then partition: rearrange the list so everything smaller than the pivot is on its left and everything else on its right. The pivot is now in its final position. Recursively sort the two sides. No merge step is needed.

The Lomuto partition uses the last item as pivot and a boundary index: everything before boundary is known to be smaller than the pivot.

Lomuto partition of [7, 2, 9, 1, 5], pivot 5
7
0
↑b↑i
2
1
9
2
1
3
5
4

Pivot is the last item, 5. b (boundary) starts at 0: nothing is known to be small yet. i = 0: 7 is not smaller than 5, so leave it.

1/6
Python
def partition(nums, lo, hi): pivot, b = nums[hi], lo for i in range(lo, hi): if nums[i] < pivot: nums[i], nums[b] = nums[b], nums[i] b += 1 nums[b], nums[hi] = nums[hi], nums[b] return b def quicksort(nums, lo=0, hi=None): if hi is None: hi = len(nums) - 1 if lo < hi: p = partition(nums, lo, hi) quicksort(nums, lo, p - 1) quicksort(nums, p + 1, hi) return nums print(quicksort([7, 2, 9, 1, 5, 3, 8]))
Output
Press Run (⌘ Enter) to see what happens.

Average O(n log n), worst O(n²). If the pivot lands near the middle, each level halves the problem, like merge sort. If it is always the smallest or largest item, one side is empty and the other has n − 1 items, so you get n levels. With "last item as pivot", that worst case happens on an already sorted list, which is common in real data. The fix is to pick a random pivot (or the median of three samples). Quicksort sorts in place with O(log n) stack space on average, and it is not stable.

Quick check
Quicksort with the last element as pivot is run on [1, 2, 3, 4, 5, ..., 10000]. What happens?
Need a nudge? A hint rules out a wrong answer.
ChallengeMedium

Quicksort partition

Write the partition step of quicksort (the Lomuto scheme).

partition(nums, lo, hi) uses nums[hi] as the pivot and rearranges nums[lo..hi] in place so that:

  • every value smaller than the pivot comes before it,
  • every other value comes after it,
  • the pivot sits at its final sorted position.

Return the pivot's final index. Values outside lo..hi must not move.

nums = [7, 2, 9, 1, 5], lo = 0, hi = 4   (pivot 5)
partition → 2,   nums is now something like [2, 1, 5, 7, 9]

Do it in one pass with O(1) extra space.

def partition(nums: list[int], lo: int, hi: int) -> int: # pivot = nums[hi]; keep a boundary of "smaller than pivot" items. pass

Quickselect: the k-th item without sorting

"Find the k-th largest element" can be done by sorting (O(n log n)) or with a min-heap of size k (O(n log k), in Heaps). Quickselect does it in O(n) on average by reusing the partition you just wrote.

After one partition, the pivot sits at its final sorted index p. If p is the index you want, you are done. If the target is to the right, everything on the left is irrelevant, so partition only the right side, and vice versa. Quicksort recurses into both sides; quickselect keeps one. That single change is the whole algorithm.

Python
import random def partition(nums, lo, hi): r = random.randint(lo, hi) # random pivot defeats sorted input nums[r], nums[hi] = nums[hi], nums[r] pivot, b = nums[hi], lo for i in range(lo, hi): if nums[i] < pivot: nums[i], nums[b] = nums[b], nums[i] b += 1 nums[b], nums[hi] = nums[hi], nums[b] return b def quickselect(nums, k): """Return the k-th smallest (k = 0 is the minimum). Reorders nums.""" lo, hi = 0, len(nums) - 1 while True: # a loop, so no recursion depth p = partition(nums, lo, hi) if p == k: return nums[p] if p < k: lo = p + 1 # answer is right of the pivot else: hi = p - 1 # answer is left of the pivot def kth_largest(nums, k): return quickselect(list(nums), len(nums) - k) assert kth_largest([3, 2, 1, 5, 6, 4], 2) == 5assert kth_largest([3, 2, 3, 1, 2, 4, 5, 5, 6], 4) == 4for _ in range(500): data = [random.randint(-20, 20) for _ in range(random.randint(1, 30))] k = random.randint(1, len(data)) assert kth_largest(data, k) == sorted(data, reverse=True)[k - 1]print(kth_largest([3, 2, 1, 5, 6, 4], 2))
Output
Press Run (⌘ Enter) to see what happens.

Why O(n) on average? A random pivot lands somewhere in the middle half most of the time, so each round throws away a constant fraction of what is left. The work is then roughly n + n/2 + n/4 + ..., which sums to about 2n. Compare quicksort, where both halves survive and every level costs n.

Worst case O(n²). If the pivot is always the smallest or largest remaining item, each round discards just one element. With a fixed pivot that happens on sorted input, which is why the code picks a random one. There is a deterministic O(n) worst-case algorithm, median of medians, which picks a pivot guaranteed to be near the middle. It is worth naming, but its constant factor is large and almost nobody writes it in an interview. Library "partial sort" functions, such as C++'s std::nth_element, use introselect: quickselect that falls back to a guaranteed method if it detects too many bad pivots.

What to say when choosing. Quickselect: O(n) average, in place, but it reorders the input and needs all the data in memory. Heap of size k: O(n log k), works on a stream and keeps the input intact. Sorting: O(n log n) but the simplest and gives you every rank at once. In Python at work, heapq.nlargest(k, nums) is usually the right call.

Quick check
Quickselect uses the last element as pivot, with no randomisation. You ask for the minimum of an already sorted list of n items. How much work does it do?
Need a nudge? A hint rules out a wrong answer.

Dutch national flag: three-way partition

Sort Colors: an array holds only 0s, 1s and 2s. Sort it in place in one pass. Counting sort works in two passes, but the one-pass answer is a three-way partition with three pointers, and it fixes a real weakness of quicksort too.

Keep this invariant at all times:

  • nums[0:low] are all 0s
  • nums[low:i] are all 1s
  • nums[i:high+1] are not yet looked at
  • nums[high+1:] are all 2s

Look at nums[i]. A 0 swaps into the 0 zone at low (and both pointers advance). A 1 is already in the right zone, so just advance i. A 2 swaps into the 2 zone at high, and high shrinks, but i does not move, because the value just swapped in from the unknown zone has not been examined yet.

Sort colors on [2, 0, 2, 1, 1, 0]
2
0
↑low↑i
0
1
2
2
1
3
1
4
0
5
↑high

Everything is unknown. nums[i] is 2.

1/5
Python
def sort_colors(nums): low, i, high = 0, 0, len(nums) - 1 while i <= high: if nums[i] == 0: nums[low], nums[i] = nums[i], nums[low] low += 1 i += 1 elif nums[i] == 2: nums[i], nums[high] = nums[high], nums[i] high -= 1 # do not move i: the swapped-in value is unseen else: i += 1 return nums assert sort_colors([2, 0, 2, 1, 1, 0]) == [0, 0, 1, 1, 2, 2]assert sort_colors([2, 0, 1]) == [0, 1, 2]assert sort_colors([]) == []import randomfor _ in range(1000): a = [random.randint(0, 2) for _ in range(random.randint(0, 12))] assert sort_colors(list(a)) == sorted(a)print(sort_colors([2, 0, 2, 1, 1, 0]))
Output
Press Run (⌘ Enter) to see what happens.

Why can i advance after swapping with low? Everything between low and i is already known to be a 1, so the value coming back from low is a 1 (or i == low and it is the 0 itself). Both cases are safe.

The same idea generalises to "less than pivot / equal / greater than pivot". Plain Lomuto partition puts all copies of the pivot on one side, so an array of a million equal values makes quicksort O(n²). A three-way partition puts the equal values in the middle and recurses only on the strictly smaller and strictly larger parts, so many duplicates make it faster, not slower. Many library quicksorts handle duplicates this way for exactly that reason.

Stability, and what your language actually does

A sort is stable if items that compare equal keep their original order. Sort orders by date, then stable-sort by customer: each customer's orders stay in date order. With an unstable sort, that second sort could scramble the dates.

AlgorithmTime (avg / worst)Extra spaceStable
Insertion sortO(n²) / O(n²)O(1)Yes
Merge sortO(n log n) / O(n log n)O(n)Yes
QuicksortO(n log n) / O(n²)O(log n)No
HeapsortO(n log n) / O(n log n)O(1)No
TimsortO(n log n) / O(n log n), O(n) on sorted runsO(n)Yes

Built-in sorts are Timsort, a hybrid of merge sort and insertion sort written for Python in 2002. It finds already-sorted runs in the data, extends short ones with insertion sort, and merges them. Real data is often partly sorted, so this is very fast in practice. Python's list.sort() and sorted() use it (CPython 3.11 refined how runs are merged), and V8, the engine in Chrome and Node.js, has used TimSort for Array.prototype.sort since 2018. Both are stable, and JavaScript's spec has required a stable sort since ES2019.

No comparison sort can beat O(n log n) in the worst case: there are n! possible orders, and each comparison can at best halve the possibilities, which takes about log₂(n!) ≈ n log n comparisons.

Beating n log n: counting sort

That limit applies to sorts that only compare items. If the keys are small integers, you can skip comparisons entirely. Counting sort counts how many times each value appears, then writes them out in order. Sorting a million exam scores from 0 to 100 takes one pass to count and one to output: O(n + k), where k is the range of values.

Python
def counting_sort(nums, max_value): counts = [0] * (max_value + 1) for x in nums: counts[x] += 1 out = [] for value, c in enumerate(counts): out.extend([value] * c) return out print(counting_sort([3, 0, 2, 3, 1, 0, 3], 3))
Output
Press Run (⌘ Enter) to see what happens.

Bucket sort generalises this: spread items into buckets by range (for example, top-k-frequent puts each number in the bucket for its count), then read the buckets in order. Both only pay off when the range k is not much larger than n.

Bucket sort in practice: Top K Frequent Elements

Return the k most frequent values. A Counter plus sorting by count is O(n log n), and a heap of size k is O(n log k). Bucket sort gets O(n) by noticing that a frequency can only be between 1 and n. So make n + 1 buckets indexed by frequency, drop each value into the bucket for its count, and read the buckets from high to low until you have k values.

Python
from collections import Counter def top_k_frequent(nums, k): counts = Counter(nums) buckets = [[] for _ in range(len(nums) + 1)] # index = frequency for value, c in counts.items(): buckets[c].append(value) out = [] for c in range(len(buckets) - 1, 0, -1): # highest frequency first for value in buckets[c]: out.append(value) if len(out) == k: return out return out assert top_k_frequent([1, 1, 1, 2, 2, 3], 2) == [1, 2]assert top_k_frequent([4], 1) == [4]assert sorted(top_k_frequent([5, 5, 6, 6, 7], 2)) == [5, 6]print(top_k_frequent([1, 1, 1, 2, 2, 3], 2))print(Counter([1, 1, 1, 2, 2, 3]).most_common(2)) # the one-liner at work
Output
Press Run (⌘ Enter) to see what happens.

Counting is O(n), there are n + 1 buckets, and each value is placed once, so the total is O(n) time and space. The pattern to remember: when the sort key is a small bounded integer (a count, an age, a score out of 100), you can bucket by it instead of comparing. In real code, Counter.most_common(k) is the readable choice; it uses a heap when k is given.

Sorting with keys and comparators

In practice you sort records, not numbers. Python takes a key function that maps each item to the value to sort by. TypeScript takes a comparator (a, b) => number: negative if a comes first, positive if b does, zero if tied.

Python
people = [("Ada", 36), ("Sam", 25), ("Priya", 36), ("Leo", 19)] print(sorted(people, key=lambda p: p[1])) # by ageprint(sorted(people, key=lambda p: (-p[1], p[0]))) # age desc, then nameprint(sorted(["banana", "Cherry", "apple"], key=str.lower))
Output
Press Run (⌘ Enter) to see what happens.

That last pair is the classic JavaScript bug. With no comparator, sort() converts items to strings and compares them, so "100" comes before "9". Always pass (a, b) => a - b for numbers. Also note that sort() mutates the array; use [...arr].sort() or the newer arr.toSorted() (ES2023) for a copy. In Python, list.sort() sorts in place and returns None, while sorted() returns a new list.

Predict the outputJavaScript

What does this print?

console.log([5, 25, 100, 1].sort().join(","))
Need a nudge? Hints walk you through it.

Comparators that compare pairs: Largest Number

Sometimes no key function exists, and the order only makes sense by comparing two items against each other. Largest Number: arrange non-negative integers to form the largest number, returned as a string. Sorting the digits as strings in reverse almost works, but "3" versus "30" breaks it: string order puts "30" first, giving "303", while "330" is larger.

The right rule compares the two possible joins: put a before b if a + b > b + a. In Python 3, sorted only accepts a key, so turn a two-argument comparator into a key with functools.cmp_to_key. TypeScript's sort takes a comparator directly.

Python
from functools import cmp_to_key def largest_number(nums): def compare(a, b): if a + b > b + a: return -1 # a goes first if a + b < b + a: return 1 return 0 parts = sorted(map(str, nums), key=cmp_to_key(compare)) joined = "".join(parts) return "0" if joined[0] == "0" else joined # [0, 0] -> "0", not "00" assert largest_number([10, 2]) == "210"assert largest_number([3, 30, 34, 5, 9]) == "9534330"assert largest_number([0, 0]) == "0"from itertools import permutationsimport randomfor _ in range(300): nums = [random.randint(0, 60) for _ in range(random.randint(1, 5))] best = max(int("".join(map(str, p))) for p in permutations(nums)) assert largest_number(nums) == str(best), numsprint(largest_number([3, 30, 34, 5, 9]))
Output
Press Run (⌘ Enter) to see what happens.

Two details interviewers check. First, the all-zeros case: [0, 0] must give "0", not "00". Second, why this comparator is a legal sort order at all. A sort only works if the comparison is consistent: if a goes before b and b before c, then a must go before c (transitivity). For "a + b versus b + a" that is true (it can be proved by treating the joins as numbers), but a comparator you invent may not be. An inconsistent comparator does not raise an error in Python or JavaScript: you get some order, which may differ between engines and inputs. That is a silent production bug, so test hand-made comparators against brute force on small inputs, as the Python block does.

Prefer key= whenever a key exists. A key is computed once per item (n calls), while a comparator is called on every comparison (about n log n calls), and keys cannot be inconsistent.

Predict the outputPython

What does this print?

print("".join(sorted(["3", "30", "34"], reverse=True)))
Need a nudge? Hints walk you through it.
Match the pairs0/6 matched

Match the situation to the best choice.

Choose an item, then its match on the other side.

Common mistakes:

  • Calling arr.sort() on numbers in JavaScript without a comparator.
  • Writing result = my_list.sort() in Python, which sets result to None.
  • Forgetting that sorting costs O(n log n) when you state the overall complexity.
  • Using < instead of <= in merge, which makes merge sort unstable.
  • Quicksort with a fixed pivot on sorted input, which hits O(n²).
  • Advancing i after swapping with high in the Dutch flag partition, which skips an unexamined value.
  • Writing a comparator that is not consistent (not transitive), which gives an arbitrary order with no error.
Key terms
divide and conquer
Split a problem into smaller pieces, solve them recursively, and combine the results.
merge sort
Split in half, sort each, merge with two pointers. O(n log n) always, O(n) space, stable.
partition
Rearrange around a pivot so smaller items are left and others right; the pivot lands in its final spot.
stable sort
Equal items keep their original relative order. Timsort and merge sort are stable; quicksort is not.
Timsort
Merge sort plus insertion sort on natural runs. Python's sort and V8's Array.prototype.sort.
counting sort
Count occurrences of small integer keys and write them out in order. O(n + k), no comparisons.
quickselect
Partition, then continue into only the side holding index k. O(n) average, O(n²) worst case.
three-way partition
Split into less than, equal to and greater than the pivot in one pass. The Dutch national flag algorithm.
cmp_to_key
Python helper in functools that turns a two-argument comparator into a key function for sorted.