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 . A million commits take twenty. The same idea underlies database indexes, where finding a key among sorted keys takes 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 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 gaps in a search and permutations in sorting, determines how many binary questions are necessary. This proves comparison sorting cannot beat , 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 sorted in ascending order, possibly with duplicates, and a value , the useful question is where 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 appears, the first element greater than , and the values in a range.
Here is the code. Read it as a machine operating on two numbers, and , 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 and , .
Maintenance. If , then , so is a valid index. If , assignment leaves , while is unchanged. If , assignment leaves , while is unchanged. In both cases still holds.
Termination. The quantity is a nonnegative integer and strictly decreases: in the first branch it becomes and in the second , because .
Conclusion. On exit, and the invariant says . Since is sorted, every with satisfies and every with satisfies . There are exactly elements less than .
Cost. If before an iteration, the next size is or . It starts at , so after iterations , which is zero once . The loop stops after at most 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.
What you should observe:
lo = middoes not advance. When and , the midpoint is and the assignment changes nothing. The state repeats and the loop does not terminate. Withlo = mid + 1the size always decreases, guaranteeing termination in the proof.hi = mid - 1loses the answer. If , index could itself be the answer. Excluding it breaks invariant . This loop is correct only for closed intervals with different initialization and condition. Mixing conventions commonly causes errors.- Rounding the midpoint up can prevent termination. With , the ceiling gives , which is not an index in the interval, and
hi = midchanges nothing if ; otherwise jumps to . - Condition
lo <= hiadmits . Then and, withhi = mid, the state does not change, producing another infinite loop. If too, leaves the array and the read fails. - An initial state violating the invariant, such as 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 . The invariant becomes and the proof is the same. The two numbers answer the remaining queries:
| Query | Value | In Python |
|---|---|---|
| How many elements are less than ? | bisect_left(a, x) | |
| How many are less than or equal? | bisect_right(a, x) | |
| How often does appear? | bisect_right(a, x) - bisect_left(a, x) | |
| Is present? | and | i < len(a) and a[i] == x |
| Elements in | bisect_left(a, v) - bisect_left(a, u) |
The half-open interval simplifies everything. Its length is , it is empty exactly when , contiguous segments and 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 possible outcomes, the insertion position , and each comparison is a yes-or-no question. By the decision-tree height bound, at least comparisons are needed in the worst case. Since for every , 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 « is false (or ) and is true (or )». The perspective changes: the array is virtual and never built, and can be anything you can evaluate.
Real domains. If is continuous and , predicate is not generally monotone because there may be several roots. The invariant «» is preserved, however, and the interval halves at each step. This is the bisection method. After steps its width is , so reaching width requires
iterations. With and , this is . 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 is unknown, or you expect the answer near the start? Exponential search, also called galloping, addresses both. Evaluate at until a true value appears, then bisect the last interval.
Proof
Let , so . The doubling phase evaluates until is true, which happens when , or : at most evaluations. Then is false and true. Bisection works in , with candidates whose last is already known true. Each evaluation halves it, requiring exactly . Total: .
∎For small , galloping greatly outperforms binary search over a huge domain: evaluations for versus 30 with . For 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 , search by galloping for each shorter-list element in the longer list. This costs comparisons, much less than 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.
What you should observe:
- Binary search makes 7 or 8 evaluations among 128 candidates wherever the transition lies, with 8 only for . The bound is because there are 129 possible answers including «none». Galloping takes 2 for up to 15 evaluations.
- Galloping pays for distance, not domain size. With , binary search needs 30 evaluations and galloping .
- Without monotonicity, the result is a transition, not necessarily the first. With the gap enabled and small , 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 removes exactly that pair’s inversion without creating or destroying another, since all other pairs retain their relative order. The array ends sorted (), so the number of shifts is . Each inserted element makes one comparison per shift plus a final stopping comparison unless it reaches the beginning. This gives comparisons, where counts elements ending at position 0. By symmetry each pair is an inversion with probability , and linearity of expectation gives .
∎Two practical consequences. Insertion sort is adaptive: if each element is at most from its place, and its cost is , linear for constant . On sorted input it makes comparisons. Selection sort always makes comparisons regardless of input, but at most 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 smallest elements of the union in order, and left[i:] and right[j:] are sorted with all their elements the last of out. It holds at 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 .
(ii) Use strong induction on length . The case is immediate. For , both halves are shorter than , 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 be the right-hand side and , so . For integer , formula equals for every . The expressions agree at the endpoints because is continuous at powers of two. Both halves and lie in , so
Since , and coincide by induction.
∎This is the worst case, which Knuth proves is attainable, and is small: for it gives 8977 comparisons versus 499500 for a quadratic sort. The average is around . The cost is auxiliary memory for merging. The bottom-up version avoids recursion, merging runs of length 1, then 2, 4, 8 and so on in passes costing each. Natural sorts start with runs already sorted in the input. With runs they cost , 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.
| Algorithm | Worst-case comparisons | Extra memory | Stable | Adaptive |
|---|---|---|---|---|
| insertion | yes | yes, | ||
| selection | always | no | no | |
| mergesort | yes | natural version only | ||
| heapsort | no | no | ||
| quicksort | (expected ) | no | no | |
| counting and radix | no comparisons | yes, with correct distribution | no |
Selection sort is unstable because a swap jumps over elements: in the minimum 1 is swapped with , yielding 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 comparisons. Could a cleverer sort do better if it obtains information only through comparisons? A comparison sort examines data through questions such as «?». For fixed , 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.
What you should observe:
- There are always 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 leaves.
- Height is at least . Depth allows at most leaves, and .
- Algorithms differ. Binary insertion and mergesort attain the bound for , 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 leaves. A binary tree of height has at most leaves by structural induction, so and . For the second claim, in at least factors are and the rest are , hence ; take logarithms.
∎This comparison-sorting lower bound, together with mergesort, makes the complexity of comparison sorting. A sharper calculation using Stirling’s formula gives , with . For 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 permutations requires 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 be the sum of leaf depths. Induct on : for , . If , the root has two subtrees with leaves, , and each subtree’s leaves are one level deeper in : . Function is convex, so Jensen’s inequality gives . Adding yields .
For the consequence, retain only the portion of the decision tree traversed by some input. Its leaves are exactly the 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 leaves and two-child internal nodes, whose depths do not exceed actual comparison counts. For uniform input, average comparisons are at least . A randomized algorithm is a mixture of deterministic trees. Averaging over seed and uniform input gives at least , 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 .
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 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 digits in base , for integers below use . 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 . After pass 1 the array is sorted by the last digit. Suppose that after pass it is sorted by the least significant digits. Pass sorts by digit . Elements with different digits get the correct order; those with the same digit retain their relative order, which by hypothesis is correct for the previous digits. Without stability the second claim fails. Each pass costs .
∎With on the order of and keys up to , and the cost is linear, . For 32-bit integers and there are 4 passes; with 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 into buckets and insertion-sorts each. For uniform input, each bucket size is binomial and insertion cost is proportional to , with expectation , linear on average. Uniformity matters: if all values fall in one bucket, the cost is quadratic.
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 merge-and-copy passes, each costing proportional to .
- Radix cost does not depend on the data, only on , and digit count. For small 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.
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.
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 shifts and show how input shape affects it.
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 . Also verify stability.
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.
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.
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
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?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 .Step 1 of 5. Which invariant do you choose?
weights to transport in the given order. Each day a truck of capacity loads consecutive packages without exceeding . Implement min_capacity(weights, days), returning the minimum capacity that transports them all within days days. Binary-search the answer: lies between the maximum weight and the sum, and if suffices, so does . 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
passMore than one answer may be correct.
Step 1 of 5. What is the base case?
count_inversions(a) to return the number of pairs with in 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
passSummary
- Binary search: invariant with sentinels, variant , at most iterations, optimal.
lower_boundandupper_bound(bisect_leftandbisect_right) provide membership, counts and ranges. - On the answer: works for any monotone predicate, with iterations over a real interval. Without monotonicity it returns an arbitrary transition. Galloping finds with evaluations without knowing the upper bound.
- Insertion and selection: insertion costs and is adaptive and stable. Selection always makes comparisons with few swaps, and is unstable.
- Mergesort: correct by strong induction, worst-case comparisons, memory, stable if the left side wins ties.
- Lower bound: a comparison-sort decision tree has leaves and height; its average depth is also .
- Without comparison: stable counting sort takes ; LSD radix takes and is correct only with stable passes. Bucket sort is linear on average only for uniform input.