Sorting Algorithms & Binary Search
Put things in order, then find anything in a few steps.
A sorted list of a million names answers "is this name here?" in at most 20 looks; an unsorted one may need a million. Sorting is the investment that makes searching, grouping and pairing cheap, and how you sort matters: at about simple steps per second, a slow sort of a million items takes over an hour, a fast one a fifth of a second.
What you’ll learn
- Explain what sorted order makes cheap: searching, finding repeats, order statistics and pairs.
- Compare insertion and selection sort with merge sort and quicksort by counting comparisons, and name the inputs that make quicksort slow.
- Explain stability, use it to sort by several keys, and describe how counting sort orders small integers without comparing them.
- Trace binary search, bound its probes by , and recognize binary search on the answer.
- Choose between sorting, binary search, selection and two pointers from the signals in a problem statement.
What order buys you
Sorting is rarely the goal. You sort so that the questions you ask next become cheap. In a sorted list, equal values sit side by side, the smallest and largest sit at the ends, the k-th smallest sits at index , and every value has a predictable place, so you can jump straight to where it must be.
The table shows what that buys on a list of numbers. The sorted column assumes the sorting is already paid for; you will see in a moment that a good sort costs only about comparisons.
| Question | Unsorted list | Sorted list |
|---|---|---|
| Is in the list? | check up to all values | binary search: at most probes |
| Does any value repeat? | compare all pairs | compare the neighboring pairs |
| What is the k-th smallest? | a separate selection algorithm | read |
| Which two values are closest? | all pairs | only the neighboring pairs |
| Do two values sum to ? | all pairs | one sweep with two pointers |
Think first You have 1,000 exam scores and want to know whether any score appears twice. How many comparisons does checking every pair take, and how many does sorting first need?
Every pair: comparisons. Sorting first: merge sort, which you will meet in two steps, needs at most 8,977 comparisons for 1,000 values, and then the 999 neighboring pairs settle the question. That is under 10,000 in all, about fifty times fewer, and the gap widens as grows.
Slow sorts: one element at a time
The most natural way to sort is the way you sort a hand of cards. Insertion sort takes the elements one at a time and slides each one left past every larger element before it. On :
- key 2 is compared with 5, which shifts right: ;
- key 4 is compared with 5 (shift) and with 2 (stop): ;
- key 1 is compared with 5, 4 and 2, and all three shift: .
That is comparisons. Selection sort works the other way round: it scans the unsorted part for the smallest element and swaps it to the front, again and again. Bubble sort, the third classic, swaps neighbors that are out of order until a pass makes no swap.
Insertion sort gets 16 keys in exactly reverse order, , so every new key is smaller than all the keys before it. How many comparisons does it make in total?
Show the answer
120 comparisons
The -th new key is compared with all keys before it: . In general it is , about : double and the work quadruples. Check it in the widget below with the reversed input.
All three grow like , which is called quadratic time: selection sort always makes comparisons, and insertion sort about on a random input and in the worst case. That is fine for 16 elements and hopeless for a million, where is : over an hour at the rule-of-thumb simple steps per second. Insertion sort has one redeeming feature. On input that is already nearly sorted, each key moves only a short way, so it finishes quickly; a sort with that property is called adaptive.
Merge sort: split, sort, merge
To beat , stop moving elements one at a time. Merge sort splits the list into two halves, sorts each half the same way, and then merges the two sorted halves. Merging is easy, because only the front element of each half can be the next smallest:
| Compare | Take | Output so far |
|---|---|---|
| 2 vs 3 | 2 | 2 |
| 5 vs 3 | 3 | 2, 3 |
| 5 vs 4 | 4 | 2, 3, 4 |
| 5 vs 8 | 5 | 2, 3, 4, 5 |
| 9 vs 8 | 8 | 2, 3, 4, 5, 8 |
| right half empty | 9 | 2, 3, 4, 5, 8, 9 |
Now count. Halving 16 elements again and again reaches single elements after levels. Merging back up, each level merges all 16 elements once, so each level costs fewer than 16 comparisons and the whole sort fewer than . In general, merge sort makes at most about comparisons, on every input. This pattern of splitting a problem, solving the parts and combining the answers is called divide and conquer.
| : insertion sort, worst case | : merge sort, about | |
|---|---|---|
| 16 | 120 | 64 |
| 1,000 | 499,500 | about 10,000 |
| 1,000,000 | : over an hour | : about 0.2 s |
Quicksort: good days and bad days
Quicksort (Hoare, 1961) divides the work differently. It picks one element, the pivot, and rearranges the list so that smaller elements come before the pivot and larger ones after it. This partition step puts the pivot in its final place; then quicksort sorts the two sides the same way. Nothing needs merging, and no buffer is needed.
When the pivot lands near the middle, each side is about half the size and quicksort does about as well as merge sort; in practice it is usually faster. But if the pivot is always the smallest or the largest element, each partition peels off one element, and the cost climbs back to .
Ties, stability, and a sort without comparisons
When two elements have equal keys, a sort may put them in either order. A stable sort promises to keep them in the order they arrived. That sounds like a detail until you sort by two keys.
Say a class list is already sorted by first name, and you now sort it by last name. A stable sort keeps the people who share a last name in first-name order, so the result is sorted by last name, then first name:
| Sorted by first name | Then stable-sorted by last name |
|---|---|
| Ana Lee | Ben Kim |
| Ben Kim | Dee Kim |
| Cal Lee | Ana Lee |
| Dee Kim | Cal Lee |
Counting sort deserves a closer look. If the keys are small whole numbers, say exam scores from 0 to 100, you never need to compare two of them: count how many times each value occurs, then write the values out in order.
def counting_sort(scores, k): # every score is an integer in 0..k
count = [0] * (k + 1)
for s in scores: # one pass to count
count[s] += 1
out = []
for v in range(k + 1): # one pass over the possible values
out.extend([v] * count[v])
return out
print(counting_sort([3, 0, 2, 3, 1, 0, 3], 3)) # [0, 0, 1, 2, 3, 3, 3]time for scores in : linear when the range is small. This version sorts bare numbers; the Optimized version places whole records, stably, using running totals of the counts.
Binary search: halve until found
Sorted data pays off when you search it. To find , compare it with the middle element. If is larger, it can only be in the right half; if smaller, only in the left half. One comparison rules out half of the candidates, and repeating that step on the half that remains is binary search.
Halving is powerful: 16 candidates need at most 5 probes, a million at most 20, a billion at most 30. In general, probes always suffice, a logarithmic number.
With repeated values, "where is ?" splits into two questions. In this array, 52 sits at indices 9, 10 and 11. The lower bound is the first index whose value is at least 52 (index 9), the upper bound the first index whose value is greater than 52 (index 12), and their difference, 3, counts the copies.
Binary search even works without an array, on any yes/no question whose answer flips once. What is the smallest daily capacity that ships ten packages, in their given order, within 4 days? A capacity that works keeps working if you raise it, so the answers read no, no, …, yes, yes, and binary search finds the flip. This is binary search on the answer.
A project's builds are numbered 1 to 100,000. A bug crept in at some build and is present in every build after it. Testing one build takes ten minutes. How do you find the first bad build fastest?
- Test builds 1, 2, 3, … until one fails
- Binary search over the build numbers: test the middle build and keep the half that must contain the first bad one
- Sort the builds by size, then test the largest first
- Test 17 builds chosen at random
Show the answer
B. Binary search over the build numbers: test the middle build and keep the half that must contain the first bad one
"Is build bad?" reads no…no yes…yes, a monotone yes/no question. Binary search finds where it flips with at most 17 tests (), under three hours, against up to 100,000 tests, about two years, for a scan. Version control systems automate exactly this search (git bisect).
Choosing the right tool
Problems rarely say "sort" or "binary search". They show signals:
- The same data is queried many times, for example "how many values are below ?" for many : sort once, then binary search each query.
- "The least (or greatest) value such that…", with a yes/no check that flips once: binary search on the answer.
- "The k-th smallest", "the median", "the top 10": selection; you need not sort everything.
- Pairs, gaps or distances between values: sort, then sweep with two pointers.
- Keys that are small integers: counting sort.
- Sorting by several keys in turn: a stable sort, least important key first.
You have sensor readings and a distance , and must count the pairs of readings that differ by at most . Which approach fits?
- Compare every pair of readings
- Binary search on the answer
- Sort the readings, then sweep with two pointers, counting for each reading how many earlier ones lie within of it
- Quickselect the median reading
Show the answer
C. Sort the readings, then sweep with two pointers, counting for each reading how many earlier ones lie within of it
After sorting, the earlier readings within of form one block that ends just before , and the block's left end only moves right as grows. Sorting costs and the sweep , against pairs for the brute force.
| Optimized lesson | What you will do there |
|---|---|
| Merge Sort, Quicksort & Heapsort | Implement the three comparison sorts, prove them correct, see why quicksort is fast on average, and use library sorts with custom keys. |
| Counting Sort, Radix Sort & Bucket Sort | Sort integers and strings in linear time without comparing them, and see why that does not contradict the lower bound. |
| Binary Search | Write lower- and upper-bound searches from an invariant that makes them correct, and find the monotone question hidden in a problem. |
| Selection & Order Statistics | Find the k-th smallest in linear time with quickselect and median of medians, and keep the top with a heap. |
Key takeaways
- Sorting is an investment: sorted data answers membership, repeats, the k-th smallest and pair questions with a few steps each.
- Insertion and selection sort grow like ( comparisons in the worst case); merge sort splits, sorts and merges with about on every input.
- Quicksort partitions around a pivot and is fast on average, but extreme pivots, such as the last element of sorted input, make it quadratic; random pivots avoid the trap.
- A stable sort keeps equal keys in arrival order, which is what makes sorting by several keys work; counting sort orders small integers in time without comparing them.
- Binary search halves a sorted range with each probe, so probes always suffice (20 for a million), and the same loop finds where any monotone yes/no question flips.
- Signals: many queries on fixed data → sort, then binary search; "the least value such that…" → binary search on the answer; "k-th smallest" → selection; pairs and gaps → sort, then two pointers; small integer keys → counting sort.
Check yourself
In the interactive lesson these are scored with your confidence, and what you miss comes back for review.
A table of orders is sorted by date. You want it grouped by customer, with each customer's orders still in date order. What do you do?
- Sort by customer with any fast sort, such as quicksort
- Sort by customer with a stable sort
- Sort by customer, then sort by date with a stable sort
- Sort by date again, then by customer with an unstable sort
Show the answer
B. Sort by customer with a stable sort
A stable sort by customer keeps the orders of each customer in their current relative order, which is date order. The last sort applied decides the main grouping; earlier sorts survive only through stability.
A quicksort always uses the last element of the range as its pivot. On which input of 1,000 distinct keys is it slowest?
- A random shuffle
- Any input: quicksort's running time does not depend on the order
- An input whose last element is the median
- Keys already in increasing order
Show the answer
D. Keys already in increasing order
On sorted input every pivot is the largest key of its range, so each partition removes just the pivot: comparisons. A random shuffle costs about 11,000 on average. Random or median-of-three pivots remove this trap.
Insertion sort takes 2 seconds on 100,000 random keys. About how long will it take on 200,000 random keys?
- About 4 seconds
- About 8 seconds
- About 2 seconds
- About 16 seconds
Show the answer
B. About 8 seconds
Insertion sort makes about comparisons on random input, so its work grows with the square of : doubling multiplies it by 4, giving about 8 seconds. An sort would take only a little over twice as long.
You need the 1,000th smallest of numbers held in memory, just once. What does the least work?
- Sort all the numbers, then read index 999
- Binary search for the 1,000th smallest
- A selection algorithm such as quickselect, which partitions like quicksort but keeps only the side that holds the answer
- Insertion sort the first 1,000 numbers and take the largest
Show the answer
C. A selection algorithm such as quickselect, which partitions like quicksort but keeps only the side that holds the answer
Selection finds one order statistic in linear expected time, while sorting determines the positions of all numbers when you need just one. The Optimized lesson Selection & Order Statistics shows how, along with heaps that keep the best so far.
You must sort exam scores, each a whole number from 0 to 100. Which method is fastest?
- Counting sort: count each of the 101 possible scores, then write them out in order
- Merge sort
- Insertion sort, since many scores repeat
- Binary search each new score into its place in a sorted array
Show the answer
A. Counting sort: count each of the 101 possible scores, then write them out in order
Counting sort takes time with possible values: two passes over the data and no comparisons at all. Merge sort would make about comparisons.
Go deeper
- Merge Sort, Quicksort & Heapsort · Three ways to sort in O(n log n) by comparing elements.
- Counting Sort, Radix Sort & Bucket Sort · Beating n log n by never comparing: sorting integers in linear time.
- Binary Search · Halve the search space every step: values, boundaries and answers.
- Selection & Order Statistics · Finding the k-th smallest without sorting everything.
Further reading
- T. H. Cormen, C. E. Leiserson, R. L. Rivest & C. Stein, Introduction to Algorithms, 4th ed. (MIT Press, 2022), chapters 2 and 6–8.
- R. Sedgewick & K. Wayne, Algorithms, 4th ed. (Addison-Wesley, 2011), chapter 2 (sorting) and section 3.1 (binary search).