Searching & Sorting
Find things in sorted data in a handful of steps, then learn how data gets sorted in the first place: the simple quadratic sorts, merge sort and quicksort, and how to use the sort your language already ships.
- Beginner
- 4 units, 12 lessons, 148 exercises
- Python, JavaScript or TypeScript
- Builds on Algorithm Foundations, a little of Recursion & Backtracking
Unit 01 · 3 lessons
Binary search
Find things in sorted data in O(log n), without off-by-one bugs
- 01Halve the search
Throw away half the list with every look
- 02Getting the bounds right
Off-by-one bugs and how to avoid them
- BOSSFirst position ≥ target
The lower bound: insertion points and counting duplicates
Read the unit guide
Binary search finds a value in a sorted list by halving. Keep a window of indexes where the target could still be. Look at the middle item: if it is too small, everything to its left is too small as well, so throw that half away. If it is too big, throw away the right half.
Each look halves the window, so n items need about log₂ n looks: 10 for a thousand items, 20 for a million. The price is that the list must be sorted. On unsorted data the "throw away half" step throws away the answer.
The classic version uses an inclusive window: lo and hi are both candidates, the loop runs while lo <= hi, and after checking mid you move past it with mid + 1 or mid - 1. Every binary search bug is a mismatch between those three decisions. lo < hi skips the last candidate; lo = mid can loop forever.
The more useful version is the lower bound: the first index whose value is at least the target. It uses a half-open window (hi starts at the length), loops while lo < hi, and sets hi = mid because mid might be the answer. It returns an insertion point even when the target is missing.
Change its < to <= and you get the upper bound: the first index whose value is greater than the target. Upper bound minus lower bound is how many times the target occurs, in O(log n).
Halve with integer division: // in Python, Math.floor in JavaScript and TypeScript. A fractional index is an error in one and undefined in the others.
Unit 02 · 3 lessons
Simple sorts
Understand sorting by doing it the slow way first
- 01Swap your way up
Bubble sort and selection sort, one pass at a time
- 02Insertion sort
Slide each item into place; nearly sorted input is nearly free
- BOSSStable or not
Keep ties in order, then sort by two keys
Read the unit guide
Three sorts fit in ten lines each, and all three are O(n²): two nested loops over the list. They are too slow for a million items, but each one teaches an idea that the fast sorts reuse.
Bubble sort compares neighbours and swaps the pairs that are out of order. One pass carries the largest value to the end, so each pass can stop one position earlier. Selection sort scans the unsorted part for its smallest value and swaps it to the front. It always makes about n²/2 comparisons, but at most n - 1 swaps.
Insertion sort is the one worth remembering. It keeps the left part sorted and slides each new item left until it fits, shifting larger items one place right. On input that is already nearly sorted the inner loop barely runs, so the whole sort is close to O(n). Real libraries switch to insertion sort for small or nearly sorted pieces.
A sort is stable when items with equal keys keep their original order. Bubble and insertion sort are stable, as long as they use a strict comparison (>, never >=). Selection sort is not: its long-distance swap can throw an item past an equal one.
Stability is what makes multi-key sorting easy: sort by the secondary key first, then by the primary key with a stable sort. The second sort keeps the first sort's order among ties.
Classic pitfalls: >= where > was meant (stability gone), a loop that stops at index 1 and never compares against index 0, and forgetting that all three are O(n²) in the worst case.
Unit 03 · 3 lessons
Fast sorts
Sort in O(n log n) by splitting the problem in two
- 01Merge two sorted lists
Two pointers, one pass, and do not forget the leftovers
- 02Merge sort
Split, sort each half, merge: O(n log n) on every input
- BOSSQuicksort
Partition around a pivot, then sort each side in place
Read the unit guide
The simple sorts fix one item per pass: n passes of up to n steps. The fast sorts split the list in two, sort each part, and need only about log₂ n levels of splitting. Each level touches every item once, so the total is O(n log n): about 20 million steps for a million items, where an O(n²) sort needs a trillion.
Merge is the building block of merge sort. Given two sorted lists, keep a pointer in each, copy the smaller of the two front items, and advance that pointer. When one list runs out, copy what is left of the other. That is O(n + m), and taking from the left list on ties keeps it stable.
Merge sort splits the list in half, sorts each half by calling itself, and merges the results. A list of 0 or 1 items is the base case. It is O(n log n) on every input and stable, but the merging needs O(n) extra memory.
Quicksort does its work before the recursion. Partition picks a pivot, moves smaller values to its left and the rest to its right, and so puts the pivot in its final position. Then each side is sorted the same way, in place.
Quicksort is only fast when the pivot splits the list roughly in half. With the last item as pivot, an already sorted list gives the worst split every time: O(n²). Real implementations pick a random pivot or the median of three.
Classic pitfalls: forgetting the leftover items after a merge, a base case that misses the 1-item list (the recursion never ends), recursing on a range that still includes the pivot, and believing quicksort is always O(n log n).
Unit 04 · 3 lessons
Sorting in practice
Use the built-in sort well, and binary search for answers
- 01The sort you already have
In place or a copy, and the trap in the default order
- 02Sort by a key
Key functions, comparators, descending order and tie-breakers
- BOSSSearch for the answer
Counting sort, then binary search with no list at all
Read the unit guide
In real code you call the sort your language ships. It is O(n log n), stable, and tuned for real data: Python and the V8 engine behind Chrome and Node use Timsort, a merge sort that switches to insertion sort on short runs. Writing your own is for learning.
Know whether a sort works in place or returns a new list. Python's list.sort() and JavaScript's array.sort() change the list itself; sorted(list) and toSorted() leave it alone and return a sorted copy. And know the JavaScript trap: with no comparator, sort() compares items as text, so 100 comes before 9.
A comparator takes two items and returns a negative number if the first goes first, a positive number if the second does, and 0 for a tie. A key function takes one item and returns the value to sort by. Python uses keys; JavaScript and TypeScript use comparators that compare keys.
Ties are broken with a second key: a tuple key in Python, a chained comparison in JavaScript. Or sort twice with a stable sort, least important key first.
Comparison sorts cannot beat O(n log n), but counting sort does not compare: with small whole-number values it tallies each value and writes them out in O(n + range).
Binary search also works on answers. When "is this value good enough?" flips from no to yes exactly once as the value grows, you can binary search for the boundary, even though no list exists. Classic pitfalls: sorting numbers as text, a comparator that returns true or false, and a search range that does not contain the answer.
Learn Searching & Sorting on your phone.
Bitpath is an iOS app in development. Join the waitlist and you get one email when it is ready to try.