Skip to content
LeetQuant
F7 Programming and Algorithms Foundations

F7 · Programming and Algorithms Foundations · Lesson 5 of 6

Sorting and Binary Search

Comparison sorts and stability, the n log n lower bound, counting sort, binary search with clean invariants and bisect, and binary search on the answer.

19 min

The sorts you should be able to discuss

AlgorithmWorst caseAverageExtra spaceStable
Insertion sortO(n2)O(n^2)O(n2)O(n^2)O(1)O(1)yes
Merge sortO(nlog⁡n)O(n \log n)O(nlog⁡n)O(n \log n)O(n)O(n)yes
QuicksortO(n2)O(n^2)O(nlog⁡n)O(n \log n)O(log⁡n)O(\log n) stackno (in-place versions)
HeapsortO(nlog⁡n)O(n \log n)O(nlog⁡n)O(n \log n)O(1)O(1)no
Timsort (Python)O(nlog⁡n)O(n \log n)O(nlog⁡n)O(n \log n)O(n)O(n)yes
  • Insertion sort costs O(n+inversions)O(n + \text{inversions}), so it is fast on nearly sorted data and is used for short runs inside hybrid sorts.
  • Quicksort's worst case appears when pivots are consistently extreme (e.g. first-element pivot on sorted input); random pivots make it unlikely. It is usually fastest in practice thanks to cache-friendly in-place partitioning.
  • Timsort finds runs that are already sorted and merges them, so sorted or nearly sorted input takes O(n)O(n).

A sort is stable if equal keys keep their input order. Stability lets you sort by several keys with successive sorts, least significant key first: sorting trades by quantity descending and then by price gives price order with larger quantities first within each price. In Python a tuple key (price, -qty) does the same in one sort.

Why comparison sorting needs n log n

Any algorithm that learns about the order only through comparisons can be drawn as a binary decision tree: each internal node is a comparison, each leaf an output order. To sort every input correctly it needs at least one leaf per permutation, so at least n!n! leaves. A binary tree of height hh has at most 2h2^h leaves, so the worst-case number of comparisons is at least

h≥log⁡2n!=nlog⁡2n−nlog⁡2e+O(log⁡n)=Ω(nlog⁡n)h \ge \log_2 n! = n \log_2 n - n \log_2 e + O(\log n) = \Omega(n \log n)

by Stirling's formula. Merge sort and heapsort meet the bound, so they are optimal up to constants. The bound says nothing about algorithms that do not compare, which is how counting sort beats it.

Worked example

the fewest comparisons for five items

What lower bound does the decision-tree argument give for sorting 5 items, and what does it say for n=106n = 10^6?

Show solution

There are 5!=1205! = 120 orderings, and 26=64<120≤128=272^6 = 64 < 120 \le 128 = 2^7, so at least ⌈log⁡2120⌉=7\lceil \log_2 120 \rceil = 7 comparisons are needed in the worst case. Seven is achievable (the Ford–Johnson merge-insertion method), whereas plain merge sort can need 8.

For n=106n = 10^6: log⁡2n!≈1.85×107\log_2 n! \approx 1.85 \times 10^7 comparisons, against nlog⁡2n≈1.99×107n \log_2 n \approx 1.99 \times 10^7. The nlog⁡2en \log_2 e correction is about 7%, and no comparison sort can do materially better than about 20 million comparisons.

Counting sort: beating the bound with small keys

When keys are integers in a known range 0..k0..k, such as prices in ticks within a day's range or ages, count them and read the counts back:

def counting_sort(keys, k):
    counts = [0] * (k + 1)
    for t in keys:
        counts[t] += 1
    return [t for t in range(k + 1) for _ in range(counts[t])]

print(counting_sort([3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5], 9))
# [1, 1, 2, 3, 3, 4, 5, 5, 5, 6, 9]

It costs O(n+k)O(n + k) time and O(k)O(k) space, so it wins when k=O(n)k = O(n) and loses when the key range is huge. To sort records by key stably, take prefix sums of the counts to get each key's starting position and place records in input order. Radix sort applies this stable pass digit by digit.

Binary search with an invariant

Off-by-one errors in binary search come from not deciding what lo and hi mean. Fix an invariant and every line follows from it. Here, the answer (the first index whose value is ≥x\ge x) always lies in the half-open range [lo, hi], with hi = len(a) meaning "no such element":

def lower_bound(a, x):
    """First index i with a[i] >= x, or len(a) if none."""
    lo, hi = 0, len(a)
    while lo < hi:
        mid = (lo + hi) // 2
        if a[mid] < x:
            lo = mid + 1    # a[mid] is too small, so the answer is right of mid
        else:
            hi = mid        # a[mid] >= x, so mid may be the answer
    return lo

The range shrinks every iteration (mid < hi, and lo moves past mid), so the loop terminates after about log⁡2n\log_2 n steps with lo == hi at the answer. Python integers do not overflow, so (lo + hi) // 2 is safe; in C++ or Java write lo + (hi - lo) / 2.

The standard library already provides this. For a sorted list:

  • bisect_left(a, x): first index with a[i] >= x, which is lower_bound above.
  • bisect_right(a, x): first index with a[i] > x.
  • insort(a, x): insert keeping order; finding the slot is O(log⁡n)O(\log n), but shifting the elements is O(n)O(n).

So bisect_right(a, x) - bisect_left(a, x) counts the copies of x, and on [1, 2, 2, 2, 3] with x = 2 the two calls return 1 and 4.

Worked example

counting trades in a price band

Trade prices for the day, sorted, are [99.5, 100.0, 100.0, 100.25, 100.5, 101.0, 101.5]. Many queries ask how many trades printed between aa and bb inclusive. Answer the query [100.0,101.0][100.0, 101.0] in O(log⁡n)O(\log n).

Show solution

The trades in [a,b][a, b] occupy a contiguous slice of the sorted list. It starts at the first price ≥a\ge a, which is bisect_left(prices, a), and ends just before the first price >b> b, which is bisect_right(prices, b):

from bisect import bisect_left, bisect_right

def count_in_range(prices, a, b):
    return bisect_right(prices, b) - bisect_left(prices, a)

prices = [99.5, 100.0, 100.0, 100.25, 100.5, 101.0, 101.5]
print(count_in_range(prices, 100.0, 101.0))   # 5

bisect_left(prices, 100.0) is 1 and bisect_right(prices, 101.0) is 6, so the answer is 6−1=56 - 1 = 5: the trades at 100.0, 100.0, 100.25, 100.5 and 101.0. Using bisect_left on both ends would drop the trade at exactly 101.0. After one O(nlog⁡n)O(n \log n) sort, each query costs O(log⁡n)O(\log n).

Binary search on the answer

Binary search works on any monotone predicate, not just arrays. If "capacity cc is enough" being true implies it is true for every larger cc, the feasible values form a range [c∗,∞)[c^*, \infty), and you can find c∗c^* by bisecting over cc with a feasibility check as the comparison. The pattern:

  1. Find bounds lo (surely infeasible or the smallest candidate) and hi (surely feasible).
  2. Write feasible(c), usually a greedy O(n)O(n) pass.
  3. Bisect: if feasible(mid) then hi = mid, else lo = mid + 1.

Total cost O(nlog⁡R)O(n \log R) for a range of RR candidates. Implied volatility is the continuous version: the option price is increasing in volatility, so you bisect on σ\sigma until the model price matches the market.

Worked example

the smallest daily limit that finishes on time

A parent order must be worked as child orders of sizes [300, 500, 200, 400, 600, 100], in this order, over at most 3 days. Each day you may execute consecutive child orders whose total is at most a daily limit cc. What is the smallest cc that works?

Show solution

Monotone predicate. If limit cc finishes in 3 days, any larger limit does too. So bisect on cc.

Bounds. cc must be at least the largest child, 600, or that child can never be executed; c=2100c = 2100 (the total) finishes in one day.

Feasibility check. Greedily fill each day until the next child would exceed cc. Filling a day as much as possible never hurts, so the greedy day count is the minimum for that cc.

def days_needed(sizes, cap):
    days, load = 1, 0
    for s in sizes:
        if load + s > cap:
            days += 1
            load = 0
        load += s
    return days

def min_capacity(sizes, d):
    lo, hi = max(sizes), sum(sizes)    # the answer lies in [lo, hi]
    while lo < hi:
        mid = (lo + hi) // 2
        if days_needed(sizes, mid) <= d:
            hi = mid                   # mid works, so try smaller
        else:
            lo = mid + 1               # mid fails, so we need more
    return lo

print(min_capacity([300, 500, 200, 400, 600, 100], 3))   # 800

Check the boundary. With c=800c = 800 the days are [300,500][300, 500], [200,400][200, 400], [600,100][600, 100]: 3 days. With c=799c = 799 the first day holds only 300 (since 300+500>799300 + 500 > 799), and the schedule [300][300], [500,200][500, 200], [400][400], [600,100][600, 100] needs 4. So 800 is the answer. The search takes 11 iterations over the 1,501 candidates from 600 to 2100, each an O(n)O(n) pass.

Knowledge check

For a = [1, 2, 2, 2, 3], what do bisect_left(a, 2) and bisect_right(a, 2) return?

Knowledge check

What is the minimum number of comparisons any comparison sort needs in the worst case to sort 4 distinct items?

Knowledge check

You sort orders by time, then sort the result by price, and want orders at the same price to stay in time order. Which algorithm guarantees that for the second sort?

Knowledge check

What property must feasible(c) have for binary search on the answer to find the smallest feasible c?

Key takeaways

  • Know the worst case, extra space and stability of insertion, merge, quick, heap and Timsort.
  • Comparison sorts need ⌈log⁡2n!⌉=Ω(nlog⁡n)\lceil \log_2 n! \rceil = \Omega(n \log n) comparisons; counting sort escapes with O(n+k)O(n + k) for small integer keys.
  • Fix a binary search invariant (here, the answer is in [lo, hi]) and derive each update from it; use bisect_left and bisect_right in Python.
  • Binary search on the answer turns "find the smallest feasible cc" into O(log⁡R)O(\log R) feasibility checks, given a monotone predicate.

Practice problems

Finished reading?

Answer the 4 knowledge checks to complete this lesson (0 done).