Command Palette

Search for a command to run...

Module 14

Sorting and Divide & Conquer

How the important sorts work inside, why O(n log n) is the limit for comparison sorts, and how to use sorting and partitioning as tools.

Intermediate 5 lessons 6 problems ~65 min of lessons

You'll rarely write a sort at work, but interviews test sorting for three reasons: merge sort and quick sort are the clearest examples of divide and conquer, their partition and merge steps solve other problems (Kth largest, counting inversions), and choosing the right sort order turns many hard problems into a simple scan.

The module covers stability and the n log n lower bound, merge sort, quick sort and quickselect, the non-comparison sorts (counting, radix, bucket), and custom comparators.

Best after: Recursion

Part 1

Learn the ideas

Part 2

Solve the problems

In order of difficulty. Each one shows the pattern it teaches.

  1. Write merge sort and quick sort yourself, and know their trade-offs.

  2. Three-way partitioning (Dutch national flag) in one pass with three pointers.

  3. Quickselect: partition once and recurse into only the side that holds the answer, O(n) on average.

  4. A custom comparator: put a before b when a + b (as strings) is bigger than b + a.

  5. Counting sort with a custom order: count values, emit them in the given order, then the rest ascending.

  6. Piggyback on merge sort: when an element from the right half is merged first, it forms an inversion with every element left in the left half.