Module contents
Lesson 2 of 33Review 85 min

Binary search and comparison sorting

A rigorous review of classical searching and sorting algorithms, focusing on the invariants that make them correct. Study binary search with half-open intervals, binary search on the answer, exponential search, insertion sort, mergesort, stability and linear-time sorting. Prove the Ω(n log n) comparison-sorting lower bound and see why counting sort and radix sort can avoid it.

After this lesson you can

  • Write correct binary searches by reasoning from a half-open interval invariant.
  • Reformulate optimization problems as binary search over a monotone predicate.
  • Prove mergesort correct by induction and establish its O(n log n) cost.
  • Prove the Ω(n log n) lower bound for comparison sorting and explain why it does not apply to radix sort.
  • Choose sorting algorithms according to stability, memory, adaptiveness and key type.

Before you start

Motivation: twenty questions suffice for a million

A bug appeared in one of the last thousand commits. With git bisect, test the middle commit: if it fails, the culprit is in the older half; otherwise, it is in the newer half. Ten tests leave one candidate because 210=1024≥10002^{10} = 1024 \ge 1000. A million commits take twenty. The same idea underlies database indexes, where finding a key among 10910^9 sorted keys takes ⌈log⁡2109⌉=30\lceil \log_2 10^9 \rceil = 30 comparisons, bisection for function roots, and finding the largest batch size that fits in memory when training networks.

The algorithm fits in five lines, which is precisely why it deserves care. In Programming Pearls, Jon Bentley recounts asking professional programmers in his courses to write binary search. After a couple of hours almost all claimed to have a correct version, but when testing for half an hour, across several courses and more than a hundred programmers, 90% found errors in their own code. Knuth notes in volume 3 of The Art of Computer Programming that binary search first appeared in 1946 and its first published error-free version did not appear until 1962. In 2006 Joshua Bloch reported on the Google Research blog that (lo + hi) / 2 overflowed on arrays larger than 2302^{30} elements, a bug present for years even in the closely scrutinized Java standard library.

This lesson reviews classical search and sorting through two themes:

  • Invariants yield correct programs. Write binary search by reasoning from a half-open interval invariant, then reuse it for searching the answer to an optimization problem, galloping in adaptive merges, and mergesort’s merge.
  • Information gives lower bounds. Counting an algorithm’s possible results, the n+1n+1 gaps in a search and n!n! permutations in sorting, determines how many binary questions are necessary. This proves comparison sorting cannot beat Ω(nlog⁡n)\Omega(n \log n), and explains how counting sort and radix sort avoid the bound by asking more than yes-or-no questions.

We assume the RAM model, asymptotic notation, and the distinction between worst and average cases from the previous lesson.

Binary search with an invariant

Given an array a[0],…,a[n−1]a[0], \dots, a[n-1] sorted in ascending order, possibly with duplicates, and a value xx, the useful question is where xx would be inserted. This is a total function with an answer for every input. It also answers membership queries and leads to other queries: how often xx appears, the first element greater than xx, and the values in a range.

Here is the code. Read it as a machine operating on two numbers, lolo and hihi, rather than as a search for an element.

def lower_bound(a, x):
    lo, hi = 0, len(a)
    while lo < hi:
        mid = lo + (hi - lo) // 2
        if a[mid] < x:
            lo = mid + 1
        else:
            hi = mid
    return lo
Proof

Initialization. With lo=0lo = 0 and hi=nhi = n, a[−1]=−∞<x≤+∞=a[n]a[-1] = -\infty < x \le +\infty = a[n].

Maintenance. If lo<hilo < hi, then lo≤mid<hilo \le mid < hi, so midmid is a valid index. If a[mid]<xa[mid] < x, assignment lo=mid+1lo = mid + 1 leaves a[lo−1]=a[mid]<xa[lo-1] = a[mid] < x, while x≤a[hi]x \le a[hi] is unchanged. If a[mid]≥xa[mid] \ge x, assignment hi=midhi = mid leaves x≤a[mid]=a[hi]x \le a[mid] = a[hi], while a[lo−1]<xa[lo-1] < x is unchanged. In both cases lo≤hilo \le hi still holds.

Termination. The quantity hi−lohi - lo is a nonnegative integer and strictly decreases: in the first branch it becomes hi−mid−1<hi−lohi - mid - 1 < hi - lo and in the second mid−lo<hi−lomid - lo < hi - lo, because lo≤mid<hilo \le mid < hi.

Conclusion. On exit, lo=hilo = hi and the invariant says a[lo−1]<x≤a[lo]a[lo-1] < x \le a[lo]. Since aa is sorted, every a[i]a[i] with i<loi < lo satisfies a[i]≤a[lo−1]<xa[i] \le a[lo-1] < x and every a[i]a[i] with i≥loi \ge lo satisfies a[i]≥a[lo]≥xa[i] \ge a[lo] \ge x. There are exactly lolo elements less than xx.

Cost. If L=hi−loL = hi - lo before an iteration, the next size is mid−lo=⌊L/2⌋mid - lo = \lfloor L/2 \rfloor or hi−mid−1=L−⌊L/2⌋−1≤⌊L/2⌋hi - mid - 1 = L - \lfloor L/2 \rfloor - 1 \le \lfloor L/2 \rfloor. It starts at L=nL = n, so after tt iterations L≤⌊n/2t⌋L \le \lfloor n/2^t \rfloor, which is zero once 2t>n2^t > n. The loop stops after at most t=⌊log⁡2n⌋+1t = \lfloor \log_2 n \rfloor + 1 iterations.

∎

The rigor of the proof rests on the loop’s small decisions. In the interactive, break them one at a time and observe the invariant.

InteractiveThe binary-search invariant
−∞2031525374858687118139141014111712191320142315+∞green: a[lo−1] < x and x ≤ a[hi]hilomid
Invariant: lo ≤ hi and a[lo−1] < x ≤ a[hi]
a[−1] = −∞ < 8 ≤ a[16] = +∞
mid = 8, a[8] = 11 ≥ 8, then hi = 8
0 / 4
Verdict of this variant for each xx (select one to try it): correct for all
05810152025
  • correct
  • wrong index
  • infinite loop
  • outside array
8
Search
Loop variants
Midpoint
While
If moving right
Otherwise
Famous variants
Statelo = 0, hi = 16
Iterations4 (maximum 5)
Returns5
Expected5
Failing xx values0 of 26
Above is hihi (orange, excluded); below is lolo (blue, included); at the sides are sentinels −∞-\infty and +∞+\infty. Green-ringed cells are a[lo−1]a[lo-1] and a[hi]a[hi]: the invariant says the left is less than xx and the right is not. Advance with the player. Change the midpoint, loop condition or assignments and inspect the verdict strip, where each square is a value of xx. Try dragging lolo and hihi before starting to violate the invariant initially. Compare lower_bound with upper_bound for xx equal to 5, 8 or 14.

What you should observe:

  • lo = mid does not advance. When hi−lo=1hi - lo = 1 and a[lo]<xa[lo] < x, the midpoint is lolo and the assignment changes nothing. The state repeats and the loop does not terminate. With lo = mid + 1 the size always decreases, guaranteeing termination in the proof.
  • hi = mid - 1 loses the answer. If a[mid]≥xa[mid] \ge x, index midmid could itself be the answer. Excluding it breaks invariant x≤a[hi]x \le a[hi]. This loop is correct only for closed intervals [lo,hi][lo, hi] with different initialization and condition. Mixing conventions commonly causes errors.
  • Rounding the midpoint up can prevent termination. With hi=lo+1hi = lo + 1, the ceiling gives mid=himid = hi, which is not an index in the interval, and hi = mid changes nothing if a[hi]≥xa[hi] \ge x; otherwise lolo jumps to hi+1hi + 1.
  • Condition lo <= hi admits lo=hilo = hi. Then mid=lomid = lo and, with hi = mid, the state does not change, producing another infinite loop. If lo=hi=nlo = hi = n too, midmid leaves the array and the read fails.
  • An initial state violating the invariant, such as hihi below the answer, produces a wrong result even if the loop itself behaves correctly. The invariant is a precondition.

Using exit condition a[mid] <= x instead of a[mid] < x gives ub⁡\operatorname{ub}. The invariant becomes a[lo−1]≤x<a[hi]a[lo-1] \le x < a[hi] and the proof is the same. The two numbers answer the remaining queries:

QueryValueIn Python
How many elements are less than xx?lb⁡(x)\operatorname{lb}(x)bisect_left(a, x)
How many are less than or equal?ub⁡(x)\operatorname{ub}(x)bisect_right(a, x)
How often does xx appear?ub⁡(x)−lb⁡(x)\operatorname{ub}(x) - \operatorname{lb}(x)bisect_right(a, x) - bisect_left(a, x)
Is xx present?lb⁡(x)<n\operatorname{lb}(x) < n and a[lb⁡(x)]=xa[\operatorname{lb}(x)] = xi < len(a) and a[i] == x
Elements in [u,v)[u, v)lb⁡(v)−lb⁡(u)\operatorname{lb}(v) - \operatorname{lb}(u)bisect_left(a, v) - bisect_left(a, u)

The half-open interval simplifies everything. Its length is hi−lohi - lo, it is empty exactly when lo=hilo = hi, contiguous segments [lo,mid)[lo, mid) and [mid,hi)[mid, hi) do not overlap, and the sentinels are easy to explain. The calculation lo + (hi - lo) // 2 cannot overflow in fixed-width integer languages, unlike (lo + hi) // 2. This does not matter in Python, but it does with numpy.int32, and the safe habit costs nothing.

Can we do better? Search has n+1n + 1 possible outcomes, the insertion position 0,1,…,n0, 1, \dots, n, and each comparison a[mid]<xa[mid] < x is a yes-or-no question. By the decision-tree height bound, at least ⌈log⁡2(n+1)⌉\lceil \log_2 (n+1) \rceil comparisons are needed in the worst case. Since ⌊log⁡2n⌋+1=⌈log⁡2(n+1)⌉\lfloor \log_2 n \rfloor + 1 = \lceil \log_2 (n+1) \rceil for every n≥1n \ge 1, binary search is optimal, with no hidden constants.

Binary search on the answer

Binary search needs a property that changes once, rather than an array. The argument above reduces to a predicate that is false, false, …, false, true, …, true.

The proof is identical, with the invariant «P(lo−1)P(lo - 1) is false (or lo=llo = l) and P(hi)P(hi) is true (or hi=hhi = h)». The perspective changes: the array is virtual and never built, and PP can be anything you can evaluate.

Real domains. If ff is continuous and f(a)<0≤f(b)f(a) < 0 \le f(b), predicate P(x)=(f(x)≥0)P(x) = (f(x) \ge 0) is not generally monotone because there may be several roots. The invariant «f(lo)<0≤f(hi)f(lo) < 0 \le f(hi)» is preserved, however, and the interval halves at each step. This is the bisection method. After kk steps its width is (b−a)/2k(b - a)/2^k, so reaching width ε\varepsilon requires

k=⌈log⁡2b−aε⌉k = \left\lceil \log_2 \frac{b - a}{\varepsilon} \right\rceil

iterations. With [a,b]=[0,1000][a, b] = [0, 1000] and ε=10−9\varepsilon = 10^{-9}, this is ⌈log⁡21012⌉=40\lceil \log_2 10^{12} \rceil = 40. Beware of floating-point arithmetic: consecutive doubles have no representable midpoint between them, so while hi - lo > eps with eps below local double spacing never terminates. A robust stopping condition is that the midpoint equals an endpoint, or a fixed number of iterations.

Exponential search and galloping

What if the bound hh is unknown, or you expect the answer near the start? Exponential search, also called galloping, addresses both. Evaluate PP at 0,1,2,4,8,…0, 1, 2, 4, 8, \dots until a true value appears, then bisect the last interval.

Proof

Let k=⌊log⁡2p⌋k = \lfloor \log_2 p \rfloor, so 2k≤p<2k+12^k \le p < 2^{k+1}. The doubling phase evaluates 0,1,2,…,2j0, 1, 2, \dots, 2^{j} until P(2j)P(2^j) is true, which happens when 2j≥p2^j \ge p, or j≤k+1j \le k + 1: at most k+3k + 3 evaluations. Then P(2j−1)P(2^{j-1}) is false and P(2j)P(2^j) true. Bisection works in (2j−1,2j](2^{j-1}, 2^j], with 2j−12^{j-1} candidates whose last is already known true. Each evaluation halves it, requiring exactly j−1≤kj - 1 \le k. Total: (k+3)+k=2k+3(k + 3) + k = 2k + 3.

∎

For small pp, galloping greatly outperforms binary search over a huge domain: 2k+3=112k + 3 = 11 evaluations for p=23p = 23 versus 30 with N=230N = 2^{30}. For pp near the upper bound it loses by roughly a factor of two. Galloping is also part of adaptive merging: to merge sorted lists of sizes m≤nm \le n, search by galloping for each shorter-list element in the longer list. This costs O(mlog⁡(1+n/m))\bigO(m \log(1 + n/m)) comparisons, much less than m+nm + n for ordinary merging when one list is very short or one list wins in long runs. Python’s list.sort uses this in Timsort galloping mode.

InteractiveBinary versus exponential search on a predicate
candidates 0 to 127: blue = false, orange = true1: P(0) = F2: P(1) = F3: P(2) = F4: P(4) = F5: P(8) = F6: P(16) = F7: P(32) = T8: P(24) = T9: P(20) = F10: P(22) = F11: P(23) = Treturns 23
11 / 11
Galloping doubles the step (squares) until PP is true, then bisects the last interval (circles): 11 evaluations for an answer at 23, without knowing NN.
  • PP false
  • PP true
  • interval still containing the transition
23
Strategy
Evaluations11 of 11
Returns23
First true23
Binary bound ⌊log⁡2N⌋+1\lfloor \log_2 N \rfloor + 18
With N=230N = 2^{30}: binary30 evaluations
With N=230N = 2^{30}: galloping11 (2⌊log₂ 23⌋ + 3)
Each row is an evaluation. The band is the interval where the first true position can remain, and the marker is the evaluated point, a square for galloping and a circle for bisection. Move the transition by dragging or using the slider and compare evaluations: binary search does nearly the same work wherever it is, while galloping depends on pp. Activate the gap: the predicate ceases to be monotone and both methods return a transition, not necessarily the first.

What you should observe:

  • Binary search makes 7 or 8 evaluations among 128 candidates wherever the transition lies, with 8 only for p=1p = 1. The bound is ⌊log⁡2128⌋+1=8\lfloor \log_2 128 \rfloor + 1 = 8 because there are 129 possible answers including «none». Galloping takes 2 for p=1p = 1 up to 15 evaluations.
  • Galloping pays for distance, not domain size. With N=230N = 2^{30}, binary search needs 30 evaluations and galloping 2⌊log⁡2p⌋+32\lfloor \log_2 p \rfloor + 3.
  • Without monotonicity, the result is a transition, not necessarily the first. With the gap enabled and small pp, binary search lands in the gap on its first evaluation and ends at its right edge. Galloping happens to succeed in this example without a general guarantee.

Elementary sorting: insertion and selection

Quadratic sorts are unsuitable for millions of items. They matter as base cases for faster algorithms, such as insertion on short runs in Timsort, and because their analysis teaches the right measure of how disordered an input is.

Proof

Swapping out-of-order neighbors a[j−1]>a[j]a[j-1] > a[j] removes exactly that pair’s inversion without creating or destroying another, since all other pairs retain their relative order. The array ends sorted (I=0I = 0), so the number of shifts is I(a)I(a). Each inserted element makes one comparison per shift plus a final stopping comparison unless it reaches the beginning. This gives I+(n−1)−fI + (n - 1) - f comparisons, where f≤n−1f \le n - 1 counts elements ending at position 0. By symmetry each pair i<ji < j is an inversion with probability 1/21/2, and linearity of expectation gives E[I]=(n2)/2\E[I] = \binom{n}{2}/2.

∎

Two practical consequences. Insertion sort is adaptive: if each element is at most kk from its place, I≤nkI \le nk and its cost is O(nk)\bigO(nk), linear for constant kk. On sorted input it makes n−1n - 1 comparisons. Selection sort always makes n(n−1)/2n(n-1)/2 comparisons regardless of input, but at most n−1n - 1 swaps, making it useful when writes cost much more than comparisons.

Mergesort: divide, sort and merge

The idea behind mergesort is that merging two sorted lists takes linear time. Sort each half, then merge them. The merge scans both lists with one pointer each, advancing the smaller head element:

def merge(left, right):
    out, i, j = [], 0, 0
    while i < len(left) and j < len(right):
        if right[j] < left[i]:          # estricta: en un empate sale primero el de la izquierda
            out.append(right[j]); j += 1
        else:
            out.append(left[i]); i += 1
    out.extend(left[i:]); out.extend(right[j:])
    return out

def merge_sort(a):
    if len(a) <= 1:
        return list(a)
    m = len(a) // 2
    return merge(merge_sort(a[:m]), merge_sort(a[m:]))
Proof

(i) The loop invariant says out contains the i+ji + j smallest elements of the union in order, and left[i:] and right[j:] are sorted with all their elements ≥\ge the last of out. It holds at i=j=0i = j = 0 and is preserved because the added element is the minimum of the two heads, which are the minima of the remaining elements. On termination one list is exhausted and the other is copied in full, already sorted. Each comparison adds an element to out, and at least one remains for the final copy, so there are at most ∣left∣+∣right∣−1\lvert left \rvert + \lvert right \rvert - 1.

(ii) Use strong induction on length nn. The case n≤1n \le 1 is immediate. For n≥2n \ge 2, both halves are shorter than nn, so by the hypothesis their outputs are sorted permutations of the originals. By (i), their merge is sorted and contains exactly the same elements.

∎
Proof

Let f(n)f(n) be the right-hand side and k=⌈log⁡2n⌉k = \lceil \log_2 n \rceil, so 2k−1<n≤2k2^{k-1} < n \le 2^k. For integer cc, formula gc(m)=mc−2c+1g_c(m) = mc - 2^c + 1 equals f(m)f(m) for every m∈[2c−1,2c]m \in [2^{c-1}, 2^c]. The expressions agree at the endpoints because ff is continuous at powers of two. Both halves ⌈n/2⌉\lceil n/2 \rceil and ⌊n/2⌋\lfloor n/2 \rfloor lie in [2k−2,2k−1][2^{k-2}, 2^{k-1}], so

f(⌈n/2⌉)+f(⌊n/2⌋)+n−1=n(k−1)−2⋅2k−1+2+n−1=nk−2k+1=f(n).f(\lceil n/2 \rceil) + f(\lfloor n/2 \rfloor) + n - 1 = n(k-1) - 2 \cdot 2^{k-1} + 2 + n - 1 = nk - 2^k + 1 = f(n).

Since f(1)=0f(1) = 0, ff and CC coincide by induction.

∎

This is the worst case, which Knuth proves is attainable, and is small: for n=1000n = 1000 it gives 8977 comparisons versus 499500 for a quadratic sort. The average is around nlog⁡2n−1.26 nn \log_2 n - 1.26\,n. The cost is Θ(n)\Theta(n) auxiliary memory for merging. The bottom-up version avoids recursion, merging runs of length 1, then 2, 4, 8 and so on in ⌈log⁡2n⌉\lceil \log_2 n \rceil passes costing O(n)\bigO(n) each. Natural sorts start with runs already sorted in the input. With rr runs they cost O(n(1+log⁡r))\bigO(n (1 + \log r)), Timsort’s second ingredient.

Stability: the tie-break that matters

This matters when sorting in two passes. Sorting first by surname and then by city gives «by city and, within each city, by surname» only if the second pass is stable. Radix sort also requires stability. The merge above is stable because its comparison is strict and on a tie it outputs the left element first, preserving their earlier order.

AlgorithmWorst-case comparisonsExtra memoryStableAdaptive
insertionΘ(n2)\Theta(n^2)O(1)\bigO(1)yesyes, Θ(n+I)\Theta(n + I)
selectionn(n−1)/2n(n-1)/2 alwaysO(1)\bigO(1)nono
mergesortn⌈log⁡2n⌉−2⌈log⁡2n⌉+1n\lceil \log_2 n \rceil - 2^{\lceil \log_2 n \rceil} + 1Θ(n)\Theta(n)yesnatural version only
heapsortΘ(nlog⁡n)\Theta(n \log n)O(1)\bigO(1)nono
quicksortΘ(n2)\Theta(n^2) (expected Θ(nlog⁡n)\Theta(n \log n))O(log⁡n)\bigO(\log n)nono
counting and radixno comparisonsΘ(n+b)\Theta(n + b)yes, with correct distributionno

Selection sort is unstable because a swap jumps over elements: in [2a,2b,1][2_a, 2_b, 1] the minimum 1 is swapped with 2a2_a, yielding [1,2b,2a][1, 2_b, 2_a] with the two 2s reversed. Any sort can be made stable by sorting (key, original position) pairs at the cost of memory and an extra comparison.

The lower bound: Ω(n log n)

Mergesort performs nlog⁡2nn \log_2 n comparisons. Could a cleverer sort do better if it obtains information only through comparisons? A comparison sort examines data through questions such as «ai<aja_i < a_j?». For fixed nn, its behavior fits in a binary tree: each internal node is a comparison, its branches are the two answers, and each leaf ends an execution with the permutation applied to the input. An input’s comparison count is its leaf’s depth.

InteractiveA sorting decision tree
depthleaves ≤01122438416532664bound: 5b<ac<ac<bd<bd<cdcbacdbad<acbdacbadd<cd<bdbcabdcad<abcdabcadd<ad<bdbacbdacd<cbadcbacdc<bc<ad<ad<cdcabcdabd<bcadbcabdd<cd<adacbadcbd<bacdbacbdd<bd<adabcadbcd<cabdcabcd
Height 5 = ⌈log⁡24!⌉\lceil \log_2 4! \rceil: this tree reaches the bound; no algorithm can do better in the worst case.
  • leaf: ascending order
  • deepest leaves
  • bound ⌈log⁡2n!⌉\lceil \log_2 n! \rceil
  • input path
Each node asks “x < y?”: the upper branch is yes and the lower branch no. Gray dashed nodes repeat a comparison whose answer was already known.
Elements
Input
Leaves24 of 24 = 4!
Height (worst case)5
Bound ⌈log⁡2n!⌉\lceil \log_2 n! \rceil5
Mean4.667 (bound 4.585)
Selected inputa=4 b=3 c=2 d=1
Its comparisons5
Complete trees for four algorithms at n=3n = 3 and n=4n = 4; elements are a,b,c,da, b, c, d and each leaf gives ascending order. Above each column are depth and the maximum leaves at that depth, 2d2^d. The dashed line is the bound ⌈log⁡2n!⌉\lceil \log_2 n! \rceil. Select a leaf to follow its input's path. Then choose «Mi algoritmo», select a dotted circle and choose what to compare. Try to give the n=4n = 4 tree height 4 or the n=3n = 3 tree height 2 and see why it cannot be done.

What you should observe:

  • There are always n!n! reachable leaves. Each input order reaches a leaf, and two different orders cannot reach the same leaf because the algorithm would apply the same permutation and leave one incorrectly sorted. The drawing shows only reachable branches. After a comparison whose answer was already known, such as gray selection-sort nodes, no input takes the other branch; the formal tree has unreachable leaves there. In general it has at least n!n! leaves.
  • Height is at least ⌈log⁡2n!⌉\lceil \log_2 n! \rceil. Depth dd allows at most 2d2^d leaves, and 24=16<242^4 = 16 < 24.
  • Algorithms differ. Binary insertion and mergesort attain the bound for n=4n = 4, with height 5. Linear insertion reaches 6, while selection always makes 6 comparisons, some redundant, as dashed gray nodes repeat known information.
Proof

The decision tree is binary and has at least n!n! leaves. A binary tree of height hh has at most 2h2^h leaves by structural induction, so 2h≥n!2^h \ge n! and h≥⌈log⁡2n!⌉h \ge \lceil \log_2 n! \rceil. For the second claim, in n!=∏k=1nkn! = \prod_{k=1}^{n} k at least n/2n/2 factors are ≥n/2\ge n/2 and the rest are ≥1\ge 1, hence n!≥(n/2)n/2n! \ge (n/2)^{n/2}; take logarithms.

∎

This comparison-sorting lower bound, together with mergesort, makes Θ(nlog⁡n)\Theta(n \log n) the complexity of comparison sorting. A sharper calculation using Stirling’s formula gives log⁡2n!=nlog⁡2n−nlog⁡2e+12log⁡2(2πn)+o(1)\log_2 n! = n \log_2 n - n \log_2 e + \tfrac12 \log_2(2\pi n) + o(1), with log⁡2e≈1.443\log_2 e \approx 1.443. For n=1000n = 1000 there are at least 8530 comparisons, and mergesort takes 8977 in the worst case, 5% more. The bound also has an information interpretation: choosing among n!n! permutations requires log⁡2n!\log_2 n! bits, the entropy of a uniform permutation, and each comparison reveals at most one bit.

What about the average case or randomness? Could a sort be slow only on rare inputs and fast on almost all others?

Proof

Let D(T)D(T) be the sum of leaf depths. Induct on LL: for L=1L = 1, D=0=1⋅log⁡21D = 0 = 1 \cdot \log_2 1. If L≥2L \ge 2, the root has two subtrees with L1+L2=LL_1 + L_2 = L leaves, L1,L2≥1L_1, L_2 \ge 1, and each subtree’s leaves are one level deeper in TT: D(T)=D(T1)+D(T2)+L≥L1log⁡2L1+L2log⁡2L2+LD(T) = D(T_1) + D(T_2) + L \ge L_1 \log_2 L_1 + L_2 \log_2 L_2 + L. Function t↦tlog⁡2tt \mapsto t \log_2 t is convex, so Jensen’s inequality gives L1log⁡2L1+L2log⁡2L2≥2⋅L2log⁡2L2=Llog⁡2L−LL_1 \log_2 L_1 + L_2 \log_2 L_2 \ge 2 \cdot \tfrac{L}{2} \log_2 \tfrac{L}{2} = L \log_2 L - L. Adding LL yields D(T)≥Llog⁡2LD(T) \ge L \log_2 L.

For the consequence, retain only the portion of the decision tree traversed by some input. Its leaves are exactly the n!n! reached, one per order. Contract any node with one child, a comparison whose answer is already known, reducing descendant leaf depths by one. The result is a tree with L=n!L = n! leaves and two-child internal nodes, whose depths do not exceed actual comparison counts. For uniform input, average comparisons are at least D/n!≥log⁡2n!D/n! \ge \log_2 n!. A randomized algorithm is a mixture of deterministic trees. Averaging over seed and uniform input gives at least log⁡2n!\log_2 n!, so some input has expected cost at least that large, a case of Yao’s principle.

∎

The bound applies to algorithms that only compare. In the RAM model, a key’s value can index an array, distinguishing as many outcomes as there are cells rather than two.

Sorting without comparisons: counting, radix and bucket

Counting sort and radix sort order integer keys without comparing them. Suppose the keys are integers in [0,k)[0, k).

Counting sort. Count occurrences of each key, convert counts to starting positions using prefix sums, and distribute elements while scanning the input left to right. Ties retain their order, so it is stable. It costs Θ(n+k)\Theta(n + k) in time and memory.

def counting_sort_by(items, key, k):
    count = [0] * (k + 1)
    for x in items:
        count[key(x) + 1] += 1
    for d in range(k):                       # count[d] pasa a ser la posición donde empieza la clave d
        count[d + 1] += count[d]
    out = [None] * len(items)
    for x in items:                          # hacia delante: estable
        out[count[key(x)]] = x
        count[key(x)] += 1
    return out

LSD radix sort. For keys of dd digits in base bb, for integers below UU use d=⌈log⁡bU⌉d = \lceil \log_b U \rceil. Sort by the least significant digit first, then the next, up to the most significant, using one stable counting-sort pass per digit. This seemingly reversed order works.

Proof

Induct on pp. After pass 1 the array is sorted by the last digit. Suppose that after pass p−1p - 1 it is sorted by the p−1p - 1 least significant digits. Pass pp sorts by digit pp. Elements with different pp digits get the correct order; those with the same pp digit retain their relative order, which by hypothesis is correct for the previous p−1p - 1 digits. Without stability the second claim fails. Each pass costs Θ(n+b)\Theta(n + b).

∎

With bb on the order of nn and keys up to U=ncU = n^c, d=cd = c and the cost is linear, Θ(c n)\Theta(c\,n). For 32-bit integers and b=256b = 256 there are 4 passes; with b=65536b = 65536 there are 2, but each touches a 65536-counter table that no longer fits in cache. The base trades passes against table size. MSD radix sorts first by the most significant digit and recurses within each bucket, without revisiting distinguishing digits, suiting variable-length strings. Bucket sort distributes reals from [0,1)[0, 1) into nn buckets and insertion-sorts each. For uniform input, each bucket size nin_i is binomial and insertion cost is proportional to ∑ini2\sum_i n_i^2, with expectation n E[n12]=n(2−1/n)=2n−1n\,\E[n_1^2] = n(2 - 1/n) = 2n - 1, linear on average. Uniformity matters: if all values fall in one bucket, the cost is quadratic.

InteractiveSorting race
time = 1233 accessesmaximum 1233
InsertionΘ(n + I)
in place: no auxiliary memory
comparisons
591
moves
595
accesses
1233
✓ sorted in 1233 accesses
MergesortΘ(n log n)
buffer
comparisons
214
moves
544
accesses
1088
✓ sorted in 1088 accesses
Radix LSD, base 32Θ(d (n + b))
buffer
comparisons
0
moves
96
accesses
864
✓ sorted in 864 accesses
Finish order: radix (864), mergesort (1088), insertion (1233). Radix makes 2 passes costing n+bn + b each and never compares keys.
  • read or compare
  • write
  • auxiliary buffer
  • sorted prefix / result
48
Radix sort
Digit base
300
Input inversions548 (max. 1128)
Radix passes2 (base 32)
Insertion total1233 accesses
Mergesort total1088 accesses
Radix total864 accesses
All three sorts use the same clock, measured in array accesses including reads and writes of radix counters: the fewest accesses wins. Press ▶ and change the input shape. Insertion wins on nearly sorted input but its cost soars on reversed input. Raise nn to 64. Change the radix base to trade fewer passes for larger tables. Finally activate the unstable pass and inspect the result.

What you should observe:

  • Insertion responds to input disorder. On almost-sorted input it uses about three accesses per element; on reversed input, an order of magnitude more. Its cost follows inversions.
  • Mergesort barely notices input order. It always makes ⌈log⁡2n⌉\lceil \log_2 n \rceil merge-and-copy passes, each costing proportional to nn.
  • Radix cost does not depend on the data, only on nn, bb and digit count. For small nn the counter table outweighs the elements. Below about 40 elements, base 1000 is worst, with one pass but 1000 counters; above that, base 2 with ten passes is worst. From roughly 32 keys, base 32 beats mergesort without comparing keys.
  • Stability matters. An unstable pass gives later passes the wrong tie order, leaving the final result unsorted even if each pass appears correct.

Implementation from scratch

Implement the above and verify it with property tests, comparing against bisect and sorted over thousands of random inputs including duplicates, empty inputs and single elements. Begin with searches and check the invariant on every iteration.

[ ]lower_bound and upper_bound with invariant checksBrowser
import bisect
import math
import random

def lower_bound(a, x):
    lo, hi = 0, len(a)
    while lo < hi:
        mid = lo + (hi - lo) // 2
        if a[mid] < x:
            lo = mid + 1
        else:
            hi = mid
    return lo

def upper_bound(a, x):
    lo, hi = 0, len(a)
    while lo < hi:
        mid = lo + (hi - lo) // 2
        if a[mid] <= x:
            lo = mid + 1
        else:
            hi = mid
    return lo

def lower_bound_checked(a, x):
    """Igual que lower_bound, pero afirma el invariante a[lo-1] < x <= a[hi] con centinelas."""
    n = len(a)
    at = lambda i: -math.inf if i < 0 else (math.inf if i >= n else a[i])
    lo, hi, iters = 0, n, 0
    while True:
        assert 0 <= lo <= hi <= n and at(lo - 1) < x <= at(hi), (lo, hi)
        if lo >= hi:
            return lo, iters
        mid = lo + (hi - lo) // 2
        iters += 1
        if a[mid] < x:
            lo = mid + 1
        else:
            hi = mid

rng = random.Random(0)
worst = 0
for _ in range(3000):
    n = rng.choice([0, 1, 2, 3, 7, 8, 9, 30, 100])
    a = sorted(rng.randint(0, 12) for _ in range(n))
    for x in range(-1, 14):
        assert lower_bound(a, x) == bisect.bisect_left(a, x)
        assert upper_bound(a, x) == bisect.bisect_right(a, x)
        r, it = lower_bound_checked(a, x)
        assert r == bisect.bisect_left(a, x)
        if n:
            assert it <= math.floor(math.log2(n)) + 1
            worst = max(worst, it - (math.floor(math.log2(n)) + 1))
print("3000 arrays aleatorios con duplicados, vacíos y extremos: todo coincide con bisect")
print("iteraciones por encima de floor(log2 n) + 1:", worst)
for n in [1, 2, 3, 15, 16, 1000]:
    a = list(range(0, 2 * n, 2))
    print(n, "elementos: máximo de iteraciones", max(lower_bound_checked(a, x)[1] for x in range(-1, 2 * n + 1)), "frente a", math.floor(math.log2(n)) + 1)

Now implement search on the answer and galloping, with integer square root, real bisection and an evaluation counter.

[ ]Search on the answer and exponential searchBrowser
import math

def first_true(lo, hi, pred):
    """Menor i en [lo, hi) con pred(i) cierto, o hi si no hay ninguno. pred debe ser monótono."""
    while lo < hi:
        mid = lo + (hi - lo) // 2
        if pred(mid):
            hi = mid
        else:
            lo = mid + 1
    return lo

def isqrt(x):
    return first_true(0, x + 2, lambda m: m * m > x) - 1

rng_vals = [0, 1, 2, 3, 15, 16, 17, 10**6, 10**18 + 7, 3**200, 2**1000 - 1]
assert all(isqrt(v) == math.isqrt(v) for v in rng_vals)
print("isqrt de 2**1000 - 1 tiene", len(str(isqrt(2**1000 - 1))), "cifras y coincide con math.isqrt")

def bisect_real(f, a, b, eps):
    """Raíz de f en [a, b] con f(a) < 0 <= f(b), por bisección. Devuelve (raíz, iteraciones)."""
    k = 0
    while b - a > eps:
        m = (a + b) / 2
        if f(m) < 0:
            a = m
        else:
            b = m
        k += 1
    return (a + b) / 2, k

f = lambda x: x * x - 2
r, k = bisect_real(f, 0.0, 2.0, 1e-9)
print(f"sqrt(2) ~ {r:.9f} con {k} iteraciones; fórmula: {math.ceil(math.log2(2.0 / 1e-9))}")

def bisect_real_robust(f, a, b, max_iter=200):
    """Parada robusta: cuando el punto medio coincide con un extremo ya no hay más dobles entre medias."""
    for k in range(max_iter):
        m = (a + b) / 2
        if m == a or m == b:
            return m, k
        if f(m) < 0:
            a = m
        else:
            b = m
    return (a + b) / 2, max_iter

r, k = bisect_real_robust(f, 0.0, 2.0)
print(f"con parada robusta: {r!r} tras {k} iteraciones (el doble más próximo a sqrt(2) es {math.sqrt(2)!r})")

def gallop(pred):
    """Búsqueda exponencial: devuelve (primer índice cierto, evaluaciones de pred)."""
    evals = 1
    if pred(0):
        return 0, evals
    prev, step = 0, 1
    while True:
        evals += 1
        if pred(step):
            break
        prev, step = step, step * 2
    lo, hi = prev + 1, step
    while lo < hi:
        mid = lo + (hi - lo) // 2
        evals += 1
        if pred(mid):
            hi = mid
        else:
            lo = mid + 1
    return lo, evals

worst_ratio = 0
for p in range(1, 4000):
    idx, ev = gallop(lambda i: i >= p)
    assert idx == p and ev <= 2 * math.floor(math.log2(p)) + 3
for p in [1, 5, 23, 1000, 10**6]:
    print(f"p = {p:>7}: galope {gallop(lambda i: i >= p)[1]:>2} evaluaciones, cota {2 * math.floor(math.log2(p)) + 3:>2}; binaria en 2**30: 30")

For elementary sorts, comparison and movement counters verify that insertion makes exactly II shifts and show how input shape affects it.

[ ]Insertion, selection and inversionsBrowser
import random

def insertion_sort(a):
    a = list(a)
    cmp = mov = 0
    for i in range(1, len(a)):
        x, j = a[i], i - 1
        while j >= 0:
            cmp += 1
            if a[j] > x:
                a[j + 1] = a[j]
                mov += 1
                j -= 1
            else:
                break
        a[j + 1] = x
    return a, cmp, mov

def selection_sort(a):
    a = list(a)
    cmp = swaps = 0
    for i in range(len(a) - 1):
        m = i
        for j in range(i + 1, len(a)):
            cmp += 1
            if a[j] < a[m]:
                m = j
        if m != i:
            a[i], a[m] = a[m], a[i]
            swaps += 1
    return a, cmp, swaps

def inversions(a):
    return sum(1 for i in range(len(a)) for j in range(i + 1, len(a)) if a[i] > a[j])

rng = random.Random(1)
for _ in range(300):
    a = rng.sample(range(1000), rng.randint(0, 25))
    s, cmp, mov = insertion_sort(a)
    assert s == sorted(a) and mov == inversions(a)
    front = sum(1 for i in range(1, len(a)) if a[i] < min(a[:i]))      # elementos que llegan a la posición 0
    assert cmp == inversions(a) + max(len(a) - 1, 0) - front
print("la inserción hace exactamente I desplazamientos y I + (n - 1) - f comparaciones")

n = 300
base = sorted(rng.sample(range(10 * n), n))
nearly = base[:]
for _ in range(6):
    i = rng.randrange(n - 1)
    nearly[i], nearly[i + 1] = nearly[i + 1], nearly[i]
forms = {"ordenada": base, "casi ordenada": nearly, "aleatoria": rng.sample(base, n), "invertida": base[::-1]}
print(f"{'entrada':<15}{'I':>7}{'insert. cmp':>13}{'insert. mov':>13}{'select. cmp':>13}")
for name, a in forms.items():
    _, c1, m1 = insertion_sort(a)
    _, c2, _ = selection_sort(a)
    print(f"{name:<15}{inversions(a):>7}{c1:>13}{m1:>13}{c2:>13}")
print("n(n-1)/2 =", n * (n - 1) // 2, " n(n-1)/4 =", n * (n - 1) // 4)

Count bottom-up mergesort comparisons against the exact worst-case formula and bound ⌈log⁡2n!⌉\lceil \log_2 n! \rceil. Also verify stability.

[ ]Bottom-up mergesort: comparisons against the boundBrowser
import math
import random

def merge_sort_bottom_up(a, key=lambda x: x):
    """Mezcla tramos de longitud 1, 2, 4, ... Devuelve (lista ordenada, número de comparaciones)."""
    src, n, cmp, width = list(a), len(a), 0, 1
    dst = src[:]
    while width < n:
        for lo in range(0, n, 2 * width):
            mid, hi = min(lo + width, n), min(lo + 2 * width, n)
            i, j, k = lo, mid, lo
            while i < mid and j < hi:
                cmp += 1
                if key(src[j]) < key(src[i]):        # estricta: el empate lo gana la izquierda
                    dst[k] = src[j]; j += 1
                else:
                    dst[k] = src[i]; i += 1
                k += 1
            while i < mid:
                dst[k] = src[i]; i += 1; k += 1
            while j < hi:
                dst[k] = src[j]; j += 1; k += 1
        src, dst = dst, src
        width *= 2
    return src, cmp

def worst_formula(n):
    k = math.ceil(math.log2(n))
    return n * k - 2**k + 1

rng = random.Random(2)
print(f"{'n':>6}{'peor caso':>11}{'medio (20 muestras)':>21}{'ceil(log2 n!)':>15}")
for n in [8, 100, 1000]:
    avg = sum(merge_sort_bottom_up(rng.sample(range(10 * n), n))[1] for _ in range(20)) / 20
    print(f"{n:>6}{worst_formula(n):>11}{avg:>21.1f}{math.ceil(math.log2(math.factorial(n))):>15}")

# El peor caso de la recurrencia coincide con la fórmula
W = {1: 0}
for n in range(2, 2001):
    W[n] = W[(n + 1) // 2] + W[n // 2] + n - 1
assert all(W[n] == worst_formula(n) for n in range(1, 2001))
print("la recurrencia C(n) = C(ceil(n/2)) + C(floor(n/2)) + n - 1 coincide con n*ceil(log2 n) - 2**ceil(log2 n) + 1 hasta n = 2000")

# Pruebas de propiedades y estabilidad: pares (clave, posición original)
for _ in range(500):
    n = rng.randint(0, 40)
    a = [(rng.randint(0, 5), i) for i in range(n)]
    s, _ = merge_sort_bottom_up(a, key=lambda p: p[0])
    assert s == sorted(a, key=lambda p: p[0])      # sorted también es estable: mismo resultado exacto
print("500 pruebas aleatorias con muchas claves repetidas: idéntico a sorted (estable)")

Finally implement stable counting sort and LSD radix sort, plus reversed distribution to reproduce the interactive’s failure.

[ ]Counting sort and LSD radix sortBrowser
import random

def counting_sort_by(items, key, k, backwards=False):
    """Counting sort por key(x) in range(k). Con backwards=True repite el error clásico: reparte desde las posiciones finales hacia delante."""
    count = [0] * (k + 1)
    for x in items:
        count[key(x) + 1] += 1
    for d in range(k):
        count[d + 1] += count[d]                      # count[d] = posición donde empieza la clave d
    out = [None] * len(items)
    if not backwards:
        for x in items:                               # hacia delante y posiciones de inicio: estable
            out[count[key(x)]] = x
            count[key(x)] += 1
    else:
        for x in items:                               # hacia delante pero rellenando cada tramo desde su final: invierte los empates
            count[key(x) + 1] -= 1
            out[count[key(x) + 1]] = x
    return out

def radix_sort(a, base=256, bits=32, backwards=False):
    """Radix LSD: una pasada de counting sort estable por cada dígito en la base dada."""
    digits = 1
    while base ** digits < 2 ** bits:
        digits += 1
    a = list(a)
    for p in range(digits):
        a = counting_sort_by(a, lambda v: (v // base ** p) % base, base, backwards)
    return a, digits

rng = random.Random(3)
a = [rng.randrange(2**32) for _ in range(3000)] + [7] * 50
for base in [2, 16, 256, 65536]:
    s, d = radix_sort(a, base)
    assert s == sorted(a)
    print(f"base {base:>6}: {d:>2} pasadas, cada una Θ(n + {base}); resultado idéntico a sorted")

# Estabilidad del counting sort: ordenar por una clave pequeña conserva la posición original
pares = [(rng.randrange(4), i) for i in range(40)]
s = counting_sort_by(pares, lambda p: p[0], 4)
assert s == sorted(pares, key=lambda p: p[0])
print("counting sort es estable: coincide con sorted(key=...) sobre pares (clave, posición)")

# El reparto con empates invertidos rompe el radix cuando hay más de una pasada
mal, _ = radix_sort(a, 256, backwards=True)
print("con el reparto inestable, ¿ordenado?", mal == sorted(a))

In libraries

In practice, libraries provide these operations, but knowing each part matters. bisect provides lower_bound and upper_bound, with an key parameter since Python 3.10. sorted and list.sort use Timsort, stable and adaptive with galloping. NumPy offers searchsorted, sort(kind=...), argsort and lexsort. NumPy’s kind parameter chooses between introsort, 'quicksort', which switches to heapsort if it stops progressing; 'heapsort'; and stable sorting, 'stable' or 'mergesort'. Depending on data type, the stable implementation uses timsort or radix sort for small integers, and the documentation says the implementation cannot be chosen directly. Indirect sorts return permutations (argsort), and stable sorts can chain keys.

[ ]bisect, sorted, NumPy and NaN valuesBrowser
import bisect
import numpy as np

a = [1, 3, 3, 3, 7, 9]
print("bisect_left / bisect_right de 3:", bisect.bisect_left(a, 3), bisect.bisect_right(a, 3))
filas = [("Ana", 31), ("Luis", 25), ("Eva", 31), ("Iván", 25), ("Rosa", 40)]
print("sorted por edad (estable):", sorted(filas, key=lambda f: f[1]))
print("bisect con key sobre la edad:", bisect.bisect_left(sorted(filas, key=lambda f: f[1]), 31, key=lambda f: f[1]))

rng = np.random.default_rng(0)
x = rng.integers(0, 50, size=40)
v = np.sort(x)
assert np.array_equal(v, np.sort(x, kind="stable")) and np.array_equal(v, np.sort(x, kind="heapsort"))

# Flotantes con muchos empates: todos los kind dan los mismos valores, pero solo los estables fijan el orden de los empates
xf = rng.integers(0, 20, size=3000) / 4.0
for kind in ["quicksort", "heapsort", "mergesort", "stable"]:
    assert np.array_equal(np.sort(xf, kind=kind), np.sort(xf))
ref = np.array(sorted(range(len(xf)), key=lambda i: xf[i]))                # orden estable de referencia
for kind in ["quicksort", "heapsort", "mergesort", "stable"]:
    print(f"argsort kind={kind!r:<12} ¿igual al orden estable?", np.array_equal(np.argsort(xf, kind=kind), ref))
print("searchsorted vectorizado:", np.searchsorted(v, [0, 10, 49, 100], side="left"), np.searchsorted(v, [0, 10, 49, 100], side="right"))

# argsort estable y lexsort: la última clave es la principal
orden = np.argsort(x, kind="stable")
assert list(orden) == sorted(range(len(x)), key=lambda i: x[i])          # mismo orden que Python con empates
apellido = np.array([3, 1, 2, 1, 3, 2])
ciudad = np.array([0, 1, 0, 0, 1, 1])
idx = np.lexsort((apellido, ciudad))                                     # ciudad primero, apellido dentro
print("lexsort (ciudad principal):", list(zip(ciudad[idx].tolist(), apellido[idx].tolist())))

# radix sort propio frente a la ordenación estable de NumPy sobre enteros de 32 bits
def radix_np(arr, base_bits=8):
    arr = arr.copy()
    for p in range(0, 32, base_bits):
        arr = arr[np.argsort((arr >> p) & ((1 << base_bits) - 1), kind="stable")]
    return arr
u = rng.integers(0, 2**32, size=5000, dtype=np.uint64).astype(np.uint32)
assert np.array_equal(radix_np(u), np.sort(u, kind="stable"))
print("radix LSD de 4 pasadas de 8 bits == np.sort(kind='stable') sobre uint32")

# NaN: NumPy los manda al final; sorted de Python no tiene un orden total y el resultado depende de la entrada
nan = float("nan")
print("np.sort:", np.sort(np.array([3.0, nan, 1.0, 2.0])))
print("sorted :", sorted([3.0, nan, 1.0, 2.0]), "y", sorted([1.0, nan, 3.0, 2.0]))

For floating-point data with many ties, the four kind return the same values, but argsort matches stable order only with 'mergesort' and 'stable', two names for the same algorithm. Introsort and heapsort do not guarantee tie order. If a permutation must be reproducible, request kind="stable".

Common mistakes

Exercises

QuizWhat breaks with lo = mid?
In lower_bound using lo, hi = 0, n, while lo < hi and mid = lo + (hi - lo) // 2, replace lo = mid + 1 with lo = mid. What happens?
ProofCorrectness of lower_bound, step by step
Prove: Let a[0..n)a[0..n) be sorted nondecreasingly and xx a value. The loop lo, hi = 0, n; while lo < hi: mid = lo + (hi - lo)//2; si a[mid] < x: lo = mid + 1; si no: hi = mid terminates and returns lo=#{i:a[i]<x}lo = \#\{i : a[i] < x\}.
0
Define a[−1]=−∞a[-1] = -\infty and a[n]=+∞a[n] = +\infty so that the invariant also makes sense at lo=0lo = 0 or hi=nhi = n.

Step 1 of 5. Which invariant do you choose?

CodeMinimum truck capacity
There are nn packages with weights to transport in the given order. Each day a truck of capacity CC loads consecutive packages without exceeding CC. Implement min_capacity(weights, days), returning the minimum capacity CC that transports them all within days days. Binary-search the answer: CC lies between the maximum weight and the sum, and if CC suffices, so does C+1C + 1. Weights are positive integers and 1 <= days <= len(weights).
def min_capacity(weights, days):
  # busca el menor C tal que se puede enviar todo en <= days días
  pass
Shift+Enter to run
NumericSorting five elements
By the decision-tree bound, what is the minimum number of comparisons required in the worst case by any comparison sort for 5 distinct elements?
QuizWhich sorts are stable?
Using each algorithm's usual formulation, strict comparisons and no key-position pairs, which sorts are stable?

More than one answer may be correct.

QuizThe inner radix pass
Sort nn 32-bit integers with LSD radix sort using 8-bit digits (base b=256b = 256). Which sort should each pass use, and why?
QuizWhy does radix sort not violate the bound?
Radix sort orders nn 32-bit integers in Θ(n)\Theta(n) time, while comparison sorting has lower bound Ω(nlog⁡n)\Omega(n \log n). How can both be true?
NumericBisection iterations
Locate a root of a continuous function that changes sign in [0,1000][0, 1000] using a final interval of width 10−910^{-9}. What is the minimum number of bisection iterations?
NumericMergesort with one hundred elements
How many comparisons does top-down mergesort make in the worst case on n=100n = 100 elements? Use the lesson's exact formula.
NumericCounting insertion-sort comparisons
Insertion sort, as formulated in the text, compares the left neighbor and stops once it is not greater. It sorts [4,3,1,5,2][4, 3, 1, 5, 2]. How many comparisons does it make?
NumericGalloping evaluations
Using the lesson's exponential search, evaluating P(0)P(0), then P(1),P(2),P(4),…P(1), P(2), P(4), \dots and bisecting the final interval, how many total evaluations of PP occur when the first true index is p=1000p = 1000?
NumericInversions in a random permutation
How many inversions does a uniformly random permutation of 20 elements have on average?
ProofThe average-case lower bound
Prove: Let TT be a binary tree with LL leaves whose internal nodes each have two children, and let D(T)D(T) be the sum of leaf depths. Then D(T)≥Llog⁡2LD(T) \ge L \log_2 L. Consequently every comparison sort makes at least log⁡2n!\log_2 n! comparisons on average on a uniform permutation of nn elements.
0
Prove this by strong induction on LL. Use convexity of ϕ(t)=tlog⁡2t\phi(t) = t \log_2 t for t>0t > 0 and define ϕ(0)=0\phi(0) = 0.

Step 1 of 5. What is the base case?

n!=∏k=1nk≥∏k=⌈n/2⌉nkn! = \prod_{k=1}^{n} k \ge \prod_{k=\lceil n/2 \rceil}^{n} k
Discard factors smaller than n/2n/2; each is at least 1, so the product can only decrease.
1/3
CodeCount inversions with mergesort
Implement count_inversions(a) to return the number of pairs i<ji < j with a[i]>a[j]a[i] > a[j] in O(nlog⁡n)\bigO(n \log n) time. Modify mergesort to count during merging: when an element from the right half precedes those remaining on the left, it forms an inversion with each of them. Ties are not inversions because the comparison is strict. Do not modify the input list.
def count_inversions(a):
  # mergesort que cuenta, en cada mezcla, las inversiones entre las dos mitades
  pass
Shift+Enter to run
QuizWhich sort for each case?
Choose the best option for each situation: (1) sort 20 elements that are almost always already sorted; (2) sort a list by surname, preserving its existing first-name order among equal surnames; (3) sort 10710^7 32-bit integers with ample extra memory.

Summary

Key idea
An invariant on a half-open interval turns binary search into a program that can be written correctly at the first attempt. The same invariant applies to searching an array, an optimization answer or a merge. Comparison sorting costs Θ(nlog⁡n)\Theta(n \log n) because there are n!n! possible results and each comparison gives one bit. Counting and radix sort avoid this bound by using operations with more than two possible outcomes.
  • Binary search: invariant a[lo−1]<x≤a[hi]a[lo-1] < x \le a[hi] with sentinels, variant hi−lohi - lo, at most ⌊log⁡2n⌋+1=⌈log⁡2(n+1)⌉\lfloor \log_2 n \rfloor + 1 = \lceil \log_2 (n+1) \rceil iterations, optimal. lower_bound and upper_bound (bisect_left and bisect_right) provide membership, counts and ranges.
  • On the answer: works for any monotone predicate, with ⌈log⁡2((b−a)/ε)⌉\lceil \log_2((b-a)/\varepsilon) \rceil iterations over a real interval. Without monotonicity it returns an arbitrary transition. Galloping finds pp with 2⌊log⁡2p⌋+32\lfloor \log_2 p \rfloor + 3 evaluations without knowing the upper bound.
  • Insertion and selection: insertion costs Θ(n+I)\Theta(n + I) and is adaptive and stable. Selection always makes n(n−1)/2n(n-1)/2 comparisons with few swaps, and is unstable.
  • Mergesort: correct by strong induction, n⌈log⁡2n⌉−2⌈log⁡2n⌉+1n\lceil \log_2 n \rceil - 2^{\lceil \log_2 n \rceil} + 1 worst-case comparisons, Θ(n)\Theta(n) memory, stable if the left side wins ties.
  • Lower bound: a comparison-sort decision tree has n!n! leaves and ≥⌈log⁡2n!⌉=Θ(nlog⁡n)\ge \lceil \log_2 n! \rceil = \Theta(n \log n) height; its average depth is also ≥log⁡2n!\ge \log_2 n!.
  • Without comparison: stable counting sort takes Θ(n+k)\Theta(n + k); LSD radix takes Θ(d(n+b))\Theta(d(n + b)) and is correct only with stable passes. Bucket sort is linear on average only for uniform input.