Simple Algorithm
Algorithms & Data Structures · Brute Force · 17 min

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 10810^8 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 ⌊log⁡2n⌋+1\lfloor \log_2 n \rfloor + 1, 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 k−1k - 1, 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 nn numbers. The sorted column assumes the sorting is already paid for; you will see in a moment that a good sort costs only about nlog⁡2nn \log_2 n comparisons.

QuestionUnsorted listSorted list
Is xx in the list?check up to all nn valuesbinary search: at most ⌊log⁡2n⌋+1\lfloor \log_2 n \rfloor + 1 probes
Does any value repeat?compare all n(n−1)/2n(n-1)/2 pairscompare the n−1n - 1 neighboring pairs
What is the k-th smallest?a separate selection algorithmread a[k−1]a[k-1]
Which two values are closest?all n(n−1)/2n(n-1)/2 pairsonly the n−1n - 1 neighboring pairs
Do two values sum to ss?all n(n−1)/2n(n-1)/2 pairsone sweep with two pointers
A hash set also finds repeats in one pass, as the Hashing topic shows. Sorting is the route that needs nothing but comparisons, and it answers all five questions at once.
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: 1000⋅999/2=499,5001000 \cdot 999 / 2 = 499{,}500 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 nn 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 [5,2,4,1][5, 2, 4, 1]:

  • key 2 is compared with 5, which shifts right: [2,5,4,1][2, 5, 4, 1];
  • key 4 is compared with 5 (shift) and with 2 (stop): [2,4,5,1][2, 4, 5, 1];
  • key 1 is compared with 5, 4 and 2, and all three shift: [1,2,4,5][1, 2, 4, 5].

That is 1+2+3=61 + 2 + 3 = 6 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.

Predict before you look

Insertion sort gets 16 keys in exactly reverse order, 16,15,…,116, 15, \dots, 1, 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 jj-th new key is compared with all jj keys before it: 1+2+⋯+15=16⋅152=1201 + 2 + \dots + 15 = \tfrac{16 \cdot 15}{2} = 120. In general it is n(n−1)/2n(n-1)/2, about n2/2n^2/2: double nn and the work quadruples. Check it in the widget below with the reversed input.

All three grow like n2n^2, which is called quadratic time: selection sort always makes n(n−1)/2n(n-1)/2 comparisons, and insertion sort about n2/4n^2/4 on a random input and n(n−1)/2n(n-1)/2 in the worst case. That is fine for 16 elements and hopeless for a million, where n2/2n^2/2 is 5×10115 \times 10^{11}: over an hour at the rule-of-thumb 10810^8 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 n2n^2, 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:

CompareTakeOutput so far
2 vs 322
5 vs 332, 3
5 vs 442, 3, 4
5 vs 852, 3, 4, 5
9 vs 882, 3, 4, 5, 8
right half empty92, 3, 4, 5, 8, 9
Merging [2,5,9][2, 5, 9] with [3,4,8][3, 4, 8]. Each comparison sends one element to the output, so halves holding nn elements in all merge with at most n−1n - 1 comparisons (5 here).

Now count. Halving 16 elements again and again reaches single elements after log⁡216=4\log_2 16 = 4 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 16×4=6416 \times 4 = 64. In general, merge sort makes at most about nlog⁡2nn \log_2 n comparisons, on every input. This pattern of splitting a problem, solving the parts and combining the answers is called divide and conquer.

nnn(n−1)/2n(n-1)/2: insertion sort, worst casenlog⁡2nn \log_2 n: merge sort, about
1612064
1,000499,500about 10,000
1,000,0005×10115 \times 10^{11}: over an hour2×1072 \times 10^7: about 0.2 s
Times use the rule of thumb of about 10810^8 simple steps per second in a compiled language. At a million elements, the two growth rates are the difference between an hour and a blink.

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 n(n−1)/2n(n-1)/2.

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 nameThen stable-sorted by last name
Ana LeeBen Kim
Ben KimDee Kim
Cal LeeAna Lee
Dee KimCal Lee
An unstable sort may return Dee Kim before Ben Kim: sorted by last name, but the first-name order is lost.

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.

python
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]

O(n+k)O(n + k) time for nn scores in 0..k0..k: linear when the range kk 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 xx, compare it with the middle element. If xx 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, ⌊log⁡2n⌋+1\lfloor \log_2 n \rfloor + 1 probes always suffice, a logarithmic number.

With repeated values, "where is xx?" 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.

Check your understanding

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?

  1. Test builds 1, 2, 3, … until one fails
  2. Binary search over the build numbers: test the middle build and keep the half that must contain the first bad one
  3. Sort the builds by size, then test the largest first
  4. 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 bb bad?" reads no…no yes…yes, a monotone yes/no question. Binary search finds where it flips with at most 17 tests (217>100,0002^{17} > 100{,}000), 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 xx?" for many xx: 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.
Check your understanding

You have n=105n = 10^5 sensor readings and a distance dd, and must count the pairs of readings that differ by at most dd. Which approach fits?

  1. Compare every pair of readings
  2. Binary search on the answer dd
  3. Sort the readings, then sweep with two pointers, counting for each reading how many earlier ones lie within dd of it
  4. 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 dd of it

After sorting, the earlier readings within dd of a[r]a[r] form one block that ends just before rr, and the block's left end only moves right as rr grows. Sorting costs O(nlog⁡n)O(n \log n) and the sweep O(n)O(n), against n(n−1)/2≈5×109n(n-1)/2 \approx 5 \times 10^9 pairs for the brute force.

Optimized lessonWhat you will do there
Merge Sort, Quicksort & HeapsortImplement the three O(nlog⁡n)O(n \log n) comparison sorts, prove them correct, see why quicksort is fast on average, and use library sorts with custom keys.
Counting Sort, Radix Sort & Bucket SortSort integers and strings in linear time without comparing them, and see why that does not contradict the nlog⁡nn \log n lower bound.
Binary SearchWrite lower- and upper-bound searches from an invariant that makes them correct, and find the monotone question hidden in a problem.
Selection & Order StatisticsFind the k-th smallest in linear time with quickselect and median of medians, and keep the top kk with a heap.
In the Optimized level, each algorithm gets its code, its correctness argument and its exact cost. The Optimal level goes on to lower bounds, landmark papers and the sorts inside real programming languages.

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 n2n^2 (n(n−1)/2n(n-1)/2 comparisons in the worst case); merge sort splits, sorts and merges with about nlog⁡2nn \log_2 n 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 O(n+k)O(n + k) time without comparing them.
  • Binary search halves a sorted range with each probe, so ⌊log⁡2n⌋+1\lfloor \log_2 n \rfloor + 1 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.

Question 1

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?

  1. Sort by customer with any fast sort, such as quicksort
  2. Sort by customer with a stable sort
  3. Sort by customer, then sort by date with a stable sort
  4. 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.

Question 2

A quicksort always uses the last element of the range as its pivot. On which input of 1,000 distinct keys is it slowest?

  1. A random shuffle
  2. Any input: quicksort's running time does not depend on the order
  3. An input whose last element is the median
  4. 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: 999+998+⋯+1=499,500999 + 998 + \dots + 1 = 499{,}500 comparisons. A random shuffle costs about 11,000 on average. Random or median-of-three pivots remove this trap.

Question 3

Insertion sort takes 2 seconds on 100,000 random keys. About how long will it take on 200,000 random keys?

  1. About 4 seconds
  2. About 8 seconds
  3. About 2 seconds
  4. About 16 seconds
Show the answer

B. About 8 seconds

Insertion sort makes about n2/4n^2/4 comparisons on random input, so its work grows with the square of nn: doubling nn multiplies it by 4, giving about 8 seconds. An nlog⁡2nn \log_2 n sort would take only a little over twice as long.

Question 4

You need the 1,000th smallest of 10710^7 numbers held in memory, just once. What does the least work?

  1. Sort all the numbers, then read index 999
  2. Binary search for the 1,000th smallest
  3. A selection algorithm such as quickselect, which partitions like quicksort but keeps only the side that holds the answer
  4. 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 10710^7 numbers when you need just one. The Optimized lesson Selection & Order Statistics shows how, along with heaps that keep the best kk so far.

Question 5

You must sort 10710^7 exam scores, each a whole number from 0 to 100. Which method is fastest?

  1. Counting sort: count each of the 101 possible scores, then write them out in order
  2. Merge sort
  3. Insertion sort, since many scores repeat
  4. 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 O(n+k)O(n + k) time with k=101k = 101 possible values: two passes over the data and no comparisons at all. Merge sort would make about nlog⁡2n≈2.3×108n \log_2 n \approx 2.3 \times 10^8 comparisons.

Go deeper

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).