The sorts you should be able to discuss
| Algorithm | Worst case | Average | Extra space | Stable |
|---|---|---|---|---|
| Insertion sort | yes | |||
| Merge sort | yes | |||
| Quicksort | stack | no (in-place versions) | ||
| Heapsort | no | |||
| Timsort (Python) | yes |
- Insertion sort costs , 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 .
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 leaves. A binary tree of height has at most leaves, so the worst-case number of comparisons is at least
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 ?
Show solutionHide solution
There are orderings, and , so at least comparisons are needed in the worst case. Seven is achievable (the Ford–Johnson merge-insertion method), whereas plain merge sort can need 8.
For : comparisons, against . The 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 , 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 time and space, so it wins when 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 ) 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 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 witha[i] >= x, which islower_boundabove.bisect_right(a, x): first index witha[i] > x.insort(a, x): insert keeping order; finding the slot is , but shifting the elements is .
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 and inclusive. Answer the query in .
Show solutionHide solution
The trades in occupy a contiguous slice of the sorted list. It starts at the first price , which is bisect_left(prices, a), and ends just before the first price , 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 : 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 sort, each query costs .
Binary search on the answer
Binary search works on any monotone predicate, not just arrays. If "capacity is enough" being true implies it is true for every larger , the feasible values form a range , and you can find by bisecting over with a feasibility check as the comparison. The pattern:
- Find bounds
lo(surely infeasible or the smallest candidate) andhi(surely feasible). - Write
feasible(c), usually a greedy pass. - Bisect: if
feasible(mid)thenhi = mid, elselo = mid + 1.
Total cost for a range of candidates. Implied volatility is the continuous version: the option price is increasing in volatility, so you bisect on 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 . What is the smallest that works?
Show solutionHide solution
Monotone predicate. If limit finishes in 3 days, any larger limit does too. So bisect on .
Bounds. must be at least the largest child, 600, or that child can never be executed; (the total) finishes in one day.
Feasibility check. Greedily fill each day until the next child would exceed . Filling a day as much as possible never hurts, so the greedy day count is the minimum for that .
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 the days are , , : 3 days. With the first day holds only 300 (since ), and the schedule , , , needs 4. So 800 is the answer. The search takes 11 iterations over the 1,501 candidates from 600 to 2100, each an 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 comparisons; counting sort escapes with for small integer keys.
- Fix a binary search invariant (here, the answer is in
[lo, hi]) and derive each update from it; usebisect_leftandbisect_rightin Python. - Binary search on the answer turns "find the smallest feasible " into feasibility checks, given a monotone predicate.
Practice problems
Finished reading?
Answer the 4 knowledge checks to complete this lesson (0 done).