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.
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.
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.
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:
- Split the list in half.
- Sort each half (recursively; a list of 0 or 1 items is already sorted).
- Merge the two sorted halves into one sorted list.
Start with six items. Split down the middle.
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.
Left half is indexes 0 to 2, right half 3 to 5. Compare the fronts: 2 vs 1.
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 <).
Press Run (⌘ Enter) to see what happens.Press Run (⌘ Enter) to see what happens.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.
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.
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.
Press Run (⌘ Enter) to see what happens.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.
[1, 2, 3, 4, 5, ..., 10000]. What happens?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.
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.
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.
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 0snums[low:i]are all 1snums[i:high+1]are not yet looked atnums[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.
Everything is unknown. nums[i] is 2.
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.
| Algorithm | Time (avg / worst) | Extra space | Stable |
|---|---|---|---|
| Insertion sort | O(n²) / O(n²) | O(1) | Yes |
| Merge sort | O(n log n) / O(n log n) | O(n) | Yes |
| Quicksort | O(n log n) / O(n²) | O(log n) | No |
| Heapsort | O(n log n) / O(n log n) | O(1) | No |
| Timsort | O(n log n) / O(n log n), O(n) on sorted runs | O(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.
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.
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.
Press Run (⌘ Enter) to see what happens.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.
What does this print?
console.log([5, 25, 100, 1].sort().join(","))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.
Press Run (⌘ Enter) to see what happens.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.
What does this print?
print("".join(sorted(["3", "30", "34"], reverse=True)))Match the situation to the best choice.
Common mistakes:
- Calling
arr.sort()on numbers in JavaScript without a comparator. - Writing
result = my_list.sort()in Python, which setsresulttoNone. - 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
iafter swapping withhighin 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.
- 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
functoolsthat turns a two-argument comparator into a key function forsorted.