Quicksort, selection and Las Vegas algorithms
A first look at randomization as a design tool. Analyze randomized quicksort with indicator variables and obtain its expected 2n ln n comparisons. Study three-way partitioning, quickselect's expected linear selection time, and median-of-medians worst-case linear time. Distinguish Las Vegas and Monte Carlo algorithms and see these ideas combined in introsort, pdqsort and CPython's adaptive mergesort.
After this lesson you can
- Compute randomized quicksort's expected comparison count using indicator variables.
- Implement Lomuto, Hoare and three-way partitioning and choose among them.
- Implement quickselect and median-of-medians and prove their expected and worst-case costs.
- Classify randomized algorithms as Las Vegas or Monte Carlo and convert between them where possible.
- Explain the design decisions of introsort, pdqsort and CPython's adaptive mergesort.
Before you start
Motivation: a quadratic worst case rarely encountered
Hoare published quicksort in 1962. Six decades later it remains the skeleton of many sorts you use without noticing: C++ std::sort, NumPy np.sort, Java primitive sorting, Rust sort_unstable and recent Go sort. Yet its worst case is . This is not merely theoretical: choosing the first element as pivot makes already sorted input, a common case, cost comparisons. How did such an algorithm become standard? The answer has three pieces recurring throughout the module:
- Randomize so the worst case is not tied to input. If the algorithm chooses pivots randomly, no fixed input is bad in expectation: bad luck depends on the algorithm’s coins. Expected cost is for every input and follows in four lines using indicator variables.
- Select without sorting. Finding the th smallest element does not require sorting. Recursing on one partition side gives expected linear time (quickselect); a careful pivot choice, median of medians, gives worst-case linear time.
- Combine techniques to avoid relying on luck. Industrial sorts such as introsort, pdqsort and CPython’s adaptive mergesort mix these ideas with deterministic safeguards for typical speed and worst-case guarantees.
Security provides context. Sorting that takes quadratic time on third-party-chosen input can enable denial of service, an algorithmic complexity attack from lesson 1 applied to quicksort. We examine how such inputs are constructed against deterministic pivots to understand why randomization and industrial safeguards are needed and how to test an implementation.
We use divide and conquer and its analysis. The master theorem does not apply because the halves have random rather than fixed sizes. Instead use expectation and linearity. The comparison-sorting lower bound is our benchmark.
Partitioning: Lomuto and Hoare
The algorithm rests on one operation. Given pivot and segment , partitioning rearranges the segment so elements below lie on one side and larger ones on the other, with the pivot at or between them. Quicksort then recurses on each side without revisiting the placed portion. Partitioning takes a linear pass; the interesting question is how unevenly the pivot divides the sides.
There are two classical schemes. Lomuto, commonly taught first and used in CLRS, maintains one boundary index:
def lomuto(a, lo, hi):
"""Pivote a[hi]. Devuelve la posición final del pivote."""
p, i = a[hi], lo
for j in range(lo, hi): # invariante: a[lo..i-1] < p y a[i..j-1] >= p
if a[j] < p:
a[i], a[j] = a[j], a[i]
i += 1
a[i], a[hi] = a[hi], a[i]
return i
The invariant holds on each iteration: elements of are below and those of are at least as large. On loop exit, swapping with the pivot puts it in its final position. It makes exactly comparisons for a segment of elements and, on a random permutation, about swaps per partition.
Hoare’s original scheme uses two indices advancing toward one another:
def hoare(a, lo, hi):
"""Pivote a[lo]. Devuelve j con a[lo..j] <= pivote <= a[j+1..hi]."""
p, i, j = a[lo], lo - 1, hi + 1
while True:
i += 1
while a[i] < p: i += 1 # salta menores desde la izquierda
j -= 1
while a[j] > p: j -= 1 # salta mayores desde la derecha
if i >= j:
return j
a[i], a[j] = a[j], a[i] # cada intercambio corrige DOS elementos mal colocados
Each swap places two elements correctly at once, so on a random permutation it makes about swaps per partition versus Lomuto’s . The code below gives versus for a complete quicksort. A crucial property with repeated keys is that both indices stop on elements equal to the pivot, splitting an all-equal segment in half. Two correctness details: recurse on and , since the pivot need not end at , and the pivot must be , not , or recursion may never progress.
The choice is an engineering decision. Lomuto is easier to prove and remember; Hoare is faster in practice and robust to duplicates. Neither avoids quicksort’s difficult worst case, where the pivot is the segment’s minimum or maximum and partitioning discards only one element.
Deterministic quicksort and the pivot adversary
With a fixed pivot rule such as first, last or middle element, whenever the pivot always falls at an extreme, and the recurrence yields . For the first-element rule, sorted input suffices. The classic improvement is median of three: choose the median of the first, middle and last elements. Sorted input then takes , and common sorted, reversed and organ-pipe patterns cease to be problematic. There remains an input that causes trouble whenever a deterministic pivot is selected from a constant-size sample.
McIlroy’s 1999 construction starts all elements without assigned values, called «gas». On each comparison, the comparator gives the most harmful response consistent with previous ones: an assigned element is smaller than an unassigned one; when two gas elements are compared, the apparent pivot candidate receives the smallest available value. Thus the sampled elements in each subproblem are among its smallest, leaving almost everything on one side of the pivot. Each partition discards elements, requiring recursion levels, each linear in the remainder. The assigned values form a permutation; rerunning the algorithm on it produces exactly the same comparisons because each response was consistent with that order. Constant sample size is essential: quicksort using the linear-time pivot selection below avoids this weakness and is in the worst case, though too slow in practice. The figure constructs adversarial inputs for three pivot rules.
Three lessons from the figure. First, fixing familiar sorted and reversed cases is no guarantee. Second, random pivots defeat this construction because the adversary’s input depends on algorithm choices it does not know. Third, important for exposed services, randomness protects only when unpredictable. A generator seeded with a constant, clock or observable value reopens the weakness; enable the known-seed switch to see the curve. Two layers of protection are random pivots using system entropy and, especially, a deterministic safeguard bounding worst-case cost even if pivots fail, as in introsort.
Randomized quicksort
If counts comparisons, we want . Solving recurrence works via generating functions and also gives variance. A clearer method, used throughout this module’s randomized algorithms, counts pairs.
Label elements by rank , assuming distinct values for now. Pair is either compared or not, and each pair is compared at most once. Comparisons are between a pivot and other elements in its segment, and the pivot is removed from subsequent subproblems. Total cost is the number of compared pairs, reducing the question to one probability per pair.
Intuition: the comparison matrix
Cells next to the diagonal are the first to inspect: always lights up, with probability 1. Consecutive values can only be separated by a pivot between them, of which there is none, so one eventually becomes pivot and is compared with the other. Distant cells rarely light because an intermediate pivot almost certainly separates them first. Sorted, reversed or random input does not change the probability: all randomness is internal and depends on ranks rather than initial order.
The result
Proof
Let , containing elements. Pivot puts all of on one side: if they are all greater, and if all smaller. Until a pivot from is chosen, the elements remain in one subproblem. Let be the first element of chosen as pivot. At that point all of is in the subproblem, whose pivot is uniform; conditioned on falling in , it is uniform on . Each of its elements is with probability regardless of previous history.
- If , the pivot is compared with every other subproblem element, including the other endpoint: and are compared.
- If with , then and the pivot sends them to different sides. They never share a subproblem or get compared. Before they were not compared either, since comparing with requires one to be pivot.
The two endpoints are two of equally likely cases, giving probability .
∎This is indicator random-variable analysis. Let . The comparison count is . By linearity of expectation, without requiring independence, absent here because the are highly correlated,
Group pairs by distance , with at each , change and separate . Simplifying with harmonic number :
where is Euler’s constant. Check : pairs and have probability 1, and has , so and the formula gives .
This holds for every input: expectation is over the algorithm’s coins alone. Compare with the lower bound : the ratio of to tends to . Randomized quicksort asymptotically makes 39% more comparisons than optimal, yet often wins in practice because its inner loop is cheap and traverses memory sequentially. At , versus gives ratio 1.29, still below the limit.
Expectation is not a guarantee: high probability
An expectation of does not say how likely a bad run is. The standard deviation of is known to grow like , small compared with the mean (under “Muchas ejecuciones” in the figure above you can see the observed deviation), but a direct guarantee is useful. We will show that recursion depth, and therefore cost, is with probability .
Proof
Fix an element and consider the chain of subproblems containing it, of sizes Call the pivot choice for a subproblem of size good if both resulting sides have size at most . This happens if the pivot rank satisfies and , that is, : a closed interval of length containing at least integers. Thus, conditioned on the entire preceding history, each choice is good with probability at least .
Each good choice multiplies the size by at most . Since sizes are integers and remains in the subproblem, there can be at most good choices in the chain for . Therefore, if the chain for has more than levels, among the first at most are good. The number of good choices in attempts stochastically dominates a , with mean . Using the multiplicative Chernoff bound and (because ):
By the union bound over the elements, the probability that any exceeds that depth is at most . Since each recursion level makes at most comparisons in total, the cost is with that probability.
∎The constant is very generous (with a random pivot and , the adversary figure shows a depth of 18 to 23 depending on the input, while the bound is ); what matters is its form: the probability of exceeding decays as a power of that can be made arbitrarily large by increasing the constant. This is the same argument structure you will use for hash tables and skip lists. Take care with the distinction between the two notions of “average,” a common source of mistakes: what we just proved is expected cost over the algorithm’s random choices, valid for any input. The average case of deterministic quicksort, also , is over an input distribution (uniform permutations) and breaks as soon as inputs no longer follow it, as the adversary just showed.
Repeated keys and three-way partitioning
The preceding analysis assumed distinct keys. With duplicates, Lomuto’s pivot separates “less than” from “greater than or equal”: if all keys are equal, everything goes to the second side and each partition discards only one element. That is on an input as innocent as an array of zeros, one of the most frequent implementation mistakes alongside a poor pivot choice. Hoare avoids the problem because it stops on equal elements and splits them between the two halves. But the best approach is to leave the elements equal to the pivot alone: they are already in place.
Dijkstra’s Dutch national flag algorithm does this in one pass, using three indices and an invariant that makes it clear: during execution, , , are unexamined, and .
def tres_vias(a, lo, hi, p):
i, m, M = lo, lo, hi
while i <= M: # el bloque sin examinar es a[i..M]
if a[i] < p:
a[m], a[i] = a[i], a[m]; m += 1; i += 1
elif a[i] > p:
a[i], a[M] = a[M], a[i]; M -= 1 # el que llega de la derecha aún no se ha examinado: i no avanza
else:
i += 1
return m, M
Each iteration examines an element and the unexamined block loses one, so there are exactly iterations: linear cost for any contents, and when all keys are equal (in one pass, without recursion). With distinct values, the same pair argument, now weighted, gives expected cost of order , where is the Shannon entropy (in bits) of key frequencies. This result of Sedgewick and Bentley, which we will not prove, says that with equally likely keys, the cost is instead of . You will measure it below. The cost of Dijkstra’s partition is that it performs more swaps than Hoare’s on distinct keys; that is why serious implementations use variants (Bentley and McIlroy leave equal elements at the ends and swap them at the end) or, like pdqsort, enable three-way partitioning only when they detect many equal elements.
Selection: quickselect
So far we have sorted. But often all we need is an order statistic: the median, a percentile, the largest values (the best candidates from a language model, the top- case you saw with argpartition in the tools module). Selection: given an array of elements and a , return the -th smallest. Sorting solves the problem in , but seems wasteful: must we sort elements far from ?
Hoare’s answer (published around the same time as his quicksort, under the name Find) is no. After partitioning around a pivot whose final rank is , either and we are done, or the -th element lies on one side, and we only need to continue there.
Recursing on both sides would turn it into quicksort. Recursing on just one makes the sizes a shrinking sequence rather than a tree.
Proof
Let be the maximum expected number of comparisons over all inputs of size at most and all ; defined this way, is nondecreasing. Partitioning costs and the pivot has rank uniformly distributed in ; in the worst case (for ) we continue on the larger side, of size . Each value between and appears at most twice:
Assume inductively for . Since (checked separately for even and odd ), we obtain
The induction starts with , and .
∎The 4 is a loose induction bound, not the actual value. The exact calculation (a classic result in Knuth) gives, for the -th element, expected comparisons, which for large and is , maximized at the median: . Compared with the for sorting, at these are versus . This is the algorithm behind numpy.partition, std::nth_element and any “unsorted top-” (you will check this in the code below). But the cost is linear only in expectation. Its tail is short (you will measure it below: none of 1,500 runs reached ), and it can be controlled with a general trick we will see in the Las Vegas section.
Median of medians: linear-time selection in the worst case
Quickselect is linear only in expectation. Can we guarantee linear time in the worst case without randomness? Yes: in 1973 Blum, Floyd, Pratt, Rivest and Tarjan achieved it with a simple idea: just any pivot is not enough; we need one guaranteed to be “in the middle,” and that pivot can be obtained recursively at a cost within the budget.
What makes it work is a count that is much clearer in a picture. Write the groups as columns sorted from bottom (smallest) to top (largest), and sort the columns by median from left to right. The pivot is the median of the row of medians. Everything below and to the left of is smaller: columns to its left have median less than , and within each, its two smallest elements are smaller than its median. Similarly, everything above and to the right is larger.
Counting elements ( groups), the guaranteed region on each side has, including the pivot itself, elements: three from each of the groups on one side (the figure excludes the pivot, so counts one fewer). Partitioning discards at least one of those two regions together with the pivot. In general, for odd group size , the guaranteed fraction is and what remains after partitioning is at most : with , .
So the algorithm calls itself twice: once on elements for the pivot, and once on at most (plus a constant) for the result, performing linear work (sorting groups of 5 and partitioning):
Proof
By substitution. For the cost is constant per element, so choose large enough for to hold in those cases; assume for , with . Then
For we have , so the expression in parentheses is at most if . Thus . The is not magic: it is what is needed to absorb the constants and in the recurrence.
∎With the Akra–Bazzi theorem the calculation takes one line: satisfies for , and then . Group size matters. With groups of 7, ; with groups of 9, : larger groups are further into the linear regime, but sorting them costs more per element. With groups of 3, and the two coefficients sum to : and the integral contributes . The standard analysis therefore gives , not a linear bound. (Variants with groups of 3 and more refined recursion are linear; what fails is this proof.) That is what the red bar in the figure shows.
In practice, median of medians is slow: its constant is considerably larger than randomized quickselect’s (you will measure it below: on the order of 5 to 8 comparisons versus on average, and sorting groups and recursing for the pivot cost more than asymptotic notation suggests). That is why it is rarely used alone: it serves as a fallback for fast quickselect, exactly as numpy.partition and std::nth_element do (introselect: quickselect until depth indicates something is wrong, then median of medians, which guarantees completion).
Las Vegas versus Monte Carlo
Quicksort and quickselect share a property: random running time, deterministic answer. Another family of randomized algorithms reverses these roles.
The names evoke gambling: in Las Vegas you may take a while, but always leave with what you are owed; in Monte Carlo the house closes at a fixed time, but you might leave with a counterfeit coin.
| Algorithm | Class | What is random | Error |
|---|---|---|---|
| Randomized quicksort | Las Vegas | Time | None |
| Quickselect | Las Vegas | Time | None |
| Hashing with retries (choose until there are no collisions) | Las Vegas | Number of attempts | None |
| Miller–Rabin test | Monte Carlo, one-sided | Answer | “Composite” is always correct; “probably prime” fails with probability per base |
| Freivalds (check ) | Monte Carlo, one-sided | Answer | “Different” is always correct; “equal” fails with probability per round |
The two classes can be converted into one another under certain conditions:
- Las Vegas to Monte Carlo: stop. If a Las Vegas algorithm has expected time , run it for at most steps and, if it has not finished, return an arbitrary answer. By Markov’s inequality, : you have obtained a fixed-time Monte Carlo algorithm with error .
- Monte Carlo to Las Vegas: verify and retry. If there is a fast answer verifier, repeat Monte Carlo until the verifier accepts. With error per attempt, the number of attempts is geometric, with expectation , and the final answer is always correct. Perfect hashing is the classic example: choose a random function, check for collisions, and repeat. Without a cheap verifier there is no useful conversion: for Miller–Rabin’s “probably prime,” the only verification is another complete primality test (such as AKS, deterministic and polynomial but much slower).
- Restart to control the tail. Combine the two: if a Las Vegas run exceeds twice its mean, abort it and restart with fresh random choices. Each attempt finishes in time with probability (Markov), so the number of attempts is bounded by a geometric variable with mean 2 and total expected cost does not exceed . This general trick turns “linear expectation” into an exponential tail.
Repeating a Monte Carlo algorithm reduces error exponentially (probability amplification, covered in depth in the lesson on randomized algorithm techniques); the complexity classes capturing these ideas, ZPP, RP and BPP, will be studied in the lesson on randomness in complexity.
Production sorting algorithms
Production sorting algorithms are not pure quicksort. They use hybrids that exploit the best of each algorithm and guard against the worst.
Introsort (Musser, 1997) is the basic recipe. It is quicksort with a median-of-three pivot that (1) tracks recursion depth and, if it exceeds , abandons that subproblem and sorts it with heapsort, which has worst case without extra memory (heaps lesson); and (2) leaves small subproblems (around 16 elements) to insertion sort, whose simple loop wins for so few elements. The result is in the worst case, deterministic and in-place: it is std::sort in C++ standard libraries and NumPy’s np.sort(kind="quicksort"), which is actually introsort (and can use vectorized variants on modern x86 processors).
pdqsort (pattern-defeating quicksort, Peters, 2021) takes the recipe further. It chooses a better pivot (median of three, or median of three medians of three in large ranges); if a partition is highly unbalanced, it breaks the pattern by swapping a few elements according to a deterministic pseudorandom sequence, and falls back to heapsort after bad partitions; if the pivot matches the previous one, it uses three-way partitioning to isolate equals; if the range seems sorted, it tries to finish with partial insertion sort, giving on sorted or nearly sorted inputs; and it partitions in blocks to reduce branch mispredictions. Go and Rust adopted it, among others (in versions of sort_unstable).
Timsort and powersort. Python’s sorted and list.sort are not quicksort: they are an adaptive, stable mergesort (stable sorting). They detect runs, ranges already sorted or strictly decreasing (the latter are reversed), extend them with binary insertion to a minimum length, and merge them pairwise, with a “galloping” mode that skips ranges when one run is far ahead of the other. What changed in CPython 3.11 is the merge policy: which runs are merged and when. Munro and Wild (2018) designed powersort, which decides each merge using the “power” of the boundary between two runs (a quantity equivalent to that boundary’s depth in a perfect binary tree over the array) and achieves a total merge cost of at most , where is the entropy (in bits) of relative run lengths: nearly optimal for those lengths. This explains why an already sorted array costs comparisons and why two or three long runs cost little more: you will see this in the code.
| Algorithm | Worst case | Extra memory | Stable | Where |
|---|---|---|---|---|
| Randomized quicksort | (negligible probability); expected | expected | No | Teaching, basis for others |
| Introsort | No | std::sort, np.sort | ||
| pdqsort | ; with patterns | No | Go, Rust (earlier versions) | |
| Timsort / powersort | ; with runs | Yes | sorted and list.sort (CPython), Java object sort | |
| Heapsort | No | Fallback for the others |
Stability explains Python’s and Java’s choice for objects: if you sort rows by one column and then another, you want the second sort to preserve the first among ties, which quicksort does not guarantee. For primitive types, where two equal numbers are indistinguishable, stability adds nothing and the fastest algorithm is used.
Implementation from scratch
First, partitioning and randomized quicksort with three schemes and a counter for comparisons and swaps. Measure how close it comes to , how many swaps Hoare saves, and what happens with repeated keys. (In three-way partitioning we count one three-outcome comparison per element.)
import random, math
def lomuto(a, lo, hi, c):
"""Pivote a[hi]. Devuelve la posición final del pivote."""
p, i = a[hi], lo
for j in range(lo, hi):
c[0] += 1
if a[j] < p:
a[i], a[j] = a[j], a[i]
i += 1
c[1] += 1
a[i], a[hi] = a[hi], a[i]
c[1] += 1
return i
def hoare(a, lo, hi, c):
"""Pivote a[lo]. Devuelve j con a[lo..j] <= pivote <= a[j+1..hi]."""
p, i, j = a[lo], lo - 1, hi + 1
while True:
while True:
i += 1
c[0] += 1
if not a[i] < p:
break
while True:
j -= 1
c[0] += 1
if not p < a[j]:
break
if i >= j:
return j
a[i], a[j] = a[j], a[i]
c[1] += 1
def tres_vias(a, lo, hi, p, c):
"""Dijkstra: deja a[lo..hi] como < p | = p | > p y devuelve (m, M): los iguales ocupan a[m..M]."""
i, m, M = lo, lo, hi
while i <= M:
c[0] += 1 # una comparación de tres vías por elemento
if a[i] < p:
a[m], a[i] = a[i], a[m]
m += 1
i += 1
c[1] += 1
elif a[i] > p:
a[i], a[M] = a[M], a[i]
M -= 1
c[1] += 1
else:
i += 1
return m, M
def quicksort(a, metodo, rng):
"""Quicksort aleatorizado (pivote uniforme). Devuelve [comparaciones, intercambios]."""
c = [0, 0]
pila = [(0, len(a) - 1)]
while pila:
lo, hi = pila.pop()
if lo >= hi:
continue
r = rng.randint(lo, hi)
if metodo == "lomuto":
a[r], a[hi] = a[hi], a[r]
k = lomuto(a, lo, hi, c)
pila += [(lo, k - 1), (k + 1, hi)]
elif metodo == "hoare":
a[r], a[lo] = a[lo], a[r]
k = hoare(a, lo, hi, c)
pila += [(lo, k), (k + 1, hi)]
else:
m, M = tres_vias(a, lo, hi, a[r], c)
pila += [(lo, m - 1), (M + 1, hi)]
return c
def esperado(n):
return 2 * (n + 1) * sum(1 / k for k in range(1, n + 1)) - 4 * n
rng = random.Random(2024)
# 1) entrada aleatoria sin repetidos
n = 4000
datos = list(range(n)); rng.shuffle(datos)
print(f"n = {n}; esperado 2(n+1)H_n - 4n = {esperado(n):.0f}; n ln n = {n * math.log(n):.0f}")
for metodo in ("lomuto", "hoare", "tres vías"):
runs = [quicksort(datos[:], metodo, rng) for _ in range(5)]
comp = sum(r[0] for r in runs) / 5
swaps = sum(r[1] for r in runs) / 5
print(f" {metodo:10s} comparaciones {comp:8.0f} ({comp / esperado(n):.3f} del esperado) intercambios / (n ln n) = {swaps / (n * math.log(n)):.2f}")
# 2) muchas claves repetidas
print("\nClaves repetidas (n = 1500):")
for nombre, gen in [("todas iguales", lambda: [7] * 1500), ("2 valores", lambda: [rng.randint(0, 1) for _ in range(1500)]),
("10 valores", lambda: [rng.randint(0, 9) for _ in range(1500)]), ("1500 distintos", lambda: rng.sample(range(1500), 1500))]:
d = gen()
filas = []
for metodo in ("lomuto", "hoare", "tres vías"):
filas.append(quicksort(d[:], metodo, rng)[0])
print(f" {nombre:15s} Lomuto {filas[0]:8d} Hoare {filas[1]:7d} tres vías {filas[2]:7d} (n^2/2 = {1500 * 1500 // 2})")Three things to look for in the output. All three schemes approach the expected value on distinct inputs (Hoare counts about 3.7 more comparisons per element: its indices cross and elements equal to the pivot are not removed, so its recurrence has a larger linear term), but Hoare makes one third as many swaps as Lomuto, and Dijkstra’s makes considerably more. With repeated keys, Lomuto sinks to quadratic cost (with all equal, of possible), while Hoare barely notices and three-way partitioning costs exactly . With distinct keys, three-way partitioning loses nothing appreciable in comparisons.
Now an adversarial test bench for a custom sort: miniature introsort with all the pieces from the previous section (random or median-of-three pivot, three-way partitioning, insertion-sort cutoff and depth-triggered heapsort fallback), and McIlroy’s adversary as a class of about fifteen lines. This is exactly the sort of test useful in continuous integration for a library sorting third-party data: construct an input against the deterministic pivot rule, verify that it degrades, and verify that the fallback and random pivot absorb it.
import random, math
def insercion(a, lo, hi, lt):
for i in range(lo + 1, hi + 1):
x, j = a[i], i - 1
while j >= lo and lt(x, a[j]):
a[j + 1] = a[j]
j -= 1
a[j + 1] = x
def heapsort(a, lo, hi, lt):
n = hi - lo + 1
def hundir(i, m):
x = a[lo + i]
while 2 * i + 1 < m:
h = 2 * i + 1
if h + 1 < m and lt(a[lo + h], a[lo + h + 1]):
h += 1
if not lt(x, a[lo + h]):
break
a[lo + i] = a[lo + h]
i = h
a[lo + i] = x
for i in range(n // 2 - 1, -1, -1):
hundir(i, n)
for m in range(n - 1, 0, -1):
a[lo], a[lo + m] = a[lo + m], a[lo]
hundir(0, m)
def tres_vias(a, lo, hi, p, lt):
i, m, M = lo, lo, hi
while i <= M:
if lt(a[i], p):
a[m], a[i] = a[i], a[m]
m += 1
i += 1
elif lt(p, a[i]):
a[i], a[M] = a[M], a[i]
M -= 1
else:
i += 1
return m, M
def elegir(a, lo, hi, lt, regla, rng):
if regla == "aleatorio":
return a[rng.randint(lo, hi)]
x, y, z = a[lo], a[(lo + hi) // 2], a[hi] # mediana de tres con solo '<'
if lt(x, y):
return y if lt(y, z) else (z if lt(x, z) else x)
return x if lt(x, z) else (z if lt(y, z) else y)
def ordenar(a, lt, regla="mediana3", salvaguarda=True, corte=16, rng=None):
"""Introsort en miniatura. Devuelve cuántas veces cayó a heapsort."""
caidas = 0
n = len(a)
limite = 2 * (n.bit_length() - 1) if salvaguarda else 10**9
pila = [(0, n - 1, limite)]
while pila:
lo, hi, prof = pila.pop()
if hi - lo + 1 <= corte:
insercion(a, lo, hi, lt)
elif prof == 0:
heapsort(a, lo, hi, lt)
caidas += 1
else:
m, M = tres_vias(a, lo, hi, elegir(a, lo, hi, lt, regla, rng), lt)
pila += [(lo, m - 1, prof - 1), (M + 1, hi, prof - 1)]
return caidas
class Adversario:
"""McIlroy (1999): fija los valores mientras el algoritmo compara. Los elementos «gas» valen más que todo lo fijado."""
GAS = float("inf")
def __init__(self, n):
self.val, self.fijos, self.candidato = [self.GAS] * n, 0, -1
def _fijar(self, x):
self.val[x], self.fijos = self.fijos, self.fijos + 1
def lt(self, x, y): # x e y son identificadores de elemento
v = self.val
if v[x] == self.GAS and v[y] == self.GAS:
self._fijar(x if x == self.candidato else y) # el candidato a pivote se fija como el menor
if v[x] == self.GAS:
self.candidato = x
elif v[y] == self.GAS:
self.candidato = y
return v[x] < v[y]
def permutacion(self):
for x, v in enumerate(self.val):
if v == self.GAS:
self._fijar(x)
return self.val
def contar(a, regla, **kw):
c = [0]
def lt(x, y):
c[0] += 1
return x < y
caidas = ordenar(a, lt, regla, **kw)
assert a == sorted(a)
return c[0], caidas
n = 500
adv = Adversario(n)
ordenar(list(range(n)), adv.lt, "mediana3", salvaguarda=False) # el adversario juega contra la mediana de tres
killer = adv.permutacion()
print(f"n = {n}: n log2 n = {n * math.log2(n):.0f}, n^2/2 = {n * n // 2}")
print("entrada del adversario:", killer[:12], "...")
rng = random.Random(1)
aleatoria = rng.sample(range(n), n)
diez_valores = [rng.randint(0, 9) for _ in range(n)]
for nombre, datos in [("aleatoria", aleatoria), ("10 valores", diez_valores), ("adversaria", killer)]:
for regla, salv in [("mediana3", False), ("mediana3", True), ("aleatorio", True)]:
comp, caidas = contar(datos[:], regla, salvaguarda=salv, rng=random.Random(5))
etiqueta = regla + (" + heapsort" if salv else "")
print(f" {nombre:11s} {etiqueta:22s} {comp:7d} comparaciones (cayó a heapsort {caidas} veces)")The adversary’s input looks unordered but structured: small and large values interleaved. Median of three without a fallback costs on the order of ( comparisons versus ). With the depth fallback, the algorithm detects something wrong at levels, falls back to heapsort on the remaining subproblem, and cost drops to about five times (the quadratic part never develops: only those 16 unbalanced partition levels are paid). With a random pivot, the adversarial input is just another input and no fallback is needed: this is what the figure showed. Also notice the ten-key row: thanks to three-way partitioning it does not even approach quadratic cost.
Now selection. Quickselect and median of medians, with comparison counters, compared with numpy.partition, and a study of quickselect’s cost distribution and tail.
import random, math
import numpy as np
def quickselect(a, k, rng):
"""k-ésimo menor (k desde 0). Devuelve (valor, comparaciones): una por elemento y partición."""
cmp = 0
while True:
p = a[rng.randrange(len(a))]
menores = [x for x in a if x < p]
mayores = [x for x in a if x > p]
cmp += len(a) - 1
iguales = len(a) - len(menores) - len(mayores)
if k < len(menores):
a = menores # solo UN lado: aquí está la diferencia con quicksort
elif k < len(menores) + iguales:
return p, cmp
else:
k -= len(menores) + iguales
a = mayores
def mediana_de_medianas(a, k, g=5):
"""k-ésimo menor en tiempo lineal en el peor caso. Devuelve (valor, comparaciones)."""
cmp = 0
def mediana_pequena(grupo): # ordenación por inserción contando comparaciones
nonlocal cmp
grupo = list(grupo)
for i in range(1, len(grupo)):
x, j = grupo[i], i - 1
while j >= 0:
cmp += 1
if not x < grupo[j]:
break
grupo[j + 1] = grupo[j]
j -= 1
grupo[j + 1] = x
return grupo[(len(grupo) - 1) // 2]
def seleccionar(a, k):
nonlocal cmp
while True:
if len(a) <= g:
a = sorted(a)
cmp += len(a) * (len(a) - 1) // 2 # cota: ordenar a mano un grupo pequeño
return a[k]
medianas = [mediana_pequena(a[i:i + g]) for i in range(0, len(a), g)]
p = seleccionar(medianas, (len(medianas) - 1) // 2)
menores = [x for x in a if x < p]
mayores = [x for x in a if x > p]
cmp += len(a) - 1
iguales = len(a) - len(menores) - len(mayores)
if k < len(menores):
a = menores
elif k < len(menores) + iguales:
return p
else:
k -= len(menores) + iguales
a = mayores
return seleccionar(list(a), k), cmp
rng = random.Random(7)
n = 4000
datos = rng.sample(range(10 * n), n)
k = n // 2
exacto = sorted(datos)[k]
print("Mediana de", n, "elementos:", exacto)
v1, c1 = quickselect(datos, k, rng)
v2, c2 = mediana_de_medianas(datos, k)
v3 = np.partition(np.array(datos), k)[k]
print(f" quickselect {v1} ({c1} comparaciones = {c1 / n:.2f} n), mediana de medianas {v2} ({c2} = {c2 / n:.2f} n), numpy.partition {v3}")
assert v1 == v2 == v3 == exacto
# coste esperado de quickselect para varios k y fórmula exacta de Knuth
def H(m):
return sum(1 / j for j in range(1, m + 1))
def knuth(n, k): # k desde 1
return 2 * ((n + 1) * H(n) - (n + 3 - k) * H(n + 1 - k) - (k + 2) * H(k) + n + 3)
print("\nQuickselect, 300 ejecuciones por k (n = 2000): media / n frente a la fórmula exacta de Knuth / n")
n = 2000
base = list(range(n))
for kk in (10, 200, 1000):
cs = [quickselect(base, kk, rng)[1] for _ in range(300)]
print(f" k = {kk:4d} medido {np.mean(cs) / n:.2f} fórmula {knuth(n, kk + 1) / n:.2f}")
# distribución del coste de la mediana
cs = np.array([quickselect(base, n // 2, rng)[1] for _ in range(1500)]) / n
print(f"\nCoste de quickselect (mediana, n = {n}, 1500 ejecuciones), en unidades de n:")
print(f" media {cs.mean():.2f} desviación {cs.std():.2f} mediana {np.median(cs):.2f} p99 {np.quantile(cs, .99):.2f} máximo {cs.max():.2f}")
print(f" P(coste > 4n) = {(cs > 4).mean():.3f}, P(> 6n) = {(cs > 6).mean():.4f}, P(> 8n) = {(cs > 8).mean():.4f} (Markov con E <= 4n: P(>= 8n) <= 0.5)")
# el peor caso de verdad: quickselect con pivote fijo frente a la mediana de medianas, sobre una entrada ordenada
def quickselect_primero(a, k):
cmp = 0
while True:
p = a[0]
menores = [x for x in a if x < p]
mayores = [x for x in a if x > p]
cmp += len(a) - 1
if k < len(menores):
a = menores
elif k == len(menores):
return p, cmp
else:
k -= len(menores) + 1
a = mayores
for m in (500, 1000, 2000):
ordenada = list(range(m))
_, cp = quickselect_primero(ordenada, m - 1)
_, cm = mediana_de_medianas(ordenada, m - 1)
print(f" entrada ordenada, n = {m:5d}: pivote fijo {cp:8d} ({cp / m:7.1f} n) mediana de medianas {cm:6d} ({cm / m:.1f} n)")The output shows that measured cost matches Knuth’s formula (3.3 to 3.4 for the median), the distribution is narrow with a short right tail (less than 2% of runs exceed and none reaches ), far below Markov’s 50% bound, and median of medians costs on the order of 5 to 8 but does not degrade on sorted input, where fixed-pivot quickselect sinks to . This difference motivates combining the two.
The production version
Python’s sorted uses only the < operator, so we can count its comparisons using a wrapper class. Check its adaptivity: sorted or reversed input costs , eight sorted runs cost about and random input comes within 1.3% of the lower bound . In NumPy, np.partition and np.argpartition implement selection (introselect), with the guarantees you already know.
import random, math
import numpy as np
class Clave:
"""Envuelve un valor y cuenta cada comparación que hace sorted (que solo usa <)."""
comparaciones = 0
__slots__ = ("v",)
def __init__(self, v):
self.v = v
def __lt__(self, otra):
Clave.comparaciones += 1
return self.v < otra.v
def coste_sorted(valores):
claves = [Clave(v) for v in valores]
Clave.comparaciones = 0
salida = sorted(claves)
assert [c.v for c in salida] == sorted(valores)
return Clave.comparaciones
rng = random.Random(3)
n = 4000
print(f"n = {n}: n log2 n = {n * math.log2(n):.0f} log2(n!) = {math.lgamma(n + 1) / math.log(2):.0f}")
aleatoria = rng.sample(range(n), n)
casi = sorted(aleatoria)
for _ in range(n // 100): # un 1 % de intercambios al azar
i, j = rng.randrange(n), rng.randrange(n)
casi[i], casi[j] = casi[j], casi[i]
casos = {
"aleatoria": aleatoria,
"ya ordenada": sorted(aleatoria),
"ordenada al revés": sorted(aleatoria, reverse=True),
"8 bloques ordenados": sum((sorted(aleatoria[i::8]) for i in range(8)), []),
"ordenada + 1 % desordenado": casi,
}
for nombre, datos in casos.items():
c = coste_sorted(datos)
print(f" {nombre:28s} {c:6d} comparaciones ({c / n:5.2f} n)")
# numpy: seleccionar sin ordenar
x = np.array(aleatoria)
k = 123
p = np.partition(x, k)
print("\nnp.partition(x, k): el elemento k queda en su sitio:", p[k] == np.sort(x)[k],
"| a la izquierda todo <=:", bool((p[:k] <= p[k]).all()), "| a la derecha todo >=:", bool((p[k + 1:] >= p[k]).all()))
idx = np.argpartition(x, k)
print("np.argpartition: x[idx[k]] es el k-ésimo menor:", x[idx[k]] == p[k], "| el bloque izquierdo no está ordenado:", not bool((p[:k] == np.sort(x)[:k]).all()))
top5 = np.sort(np.partition(x, -5)[-5:])[::-1]
print("5 mayores con partition + sort de 5 elementos:", top5, " = ", sorted(aleatoria)[-5:][::-1])The top- recipe in the last line (partition and then sorting only the selected elements) costs instead of : this is the idea used by decoders sampling from a vocabulary of tens of thousands of tokens with top-, and the same idea you saw with argpartition in the tools module.
Common mistakes
Exercises
Step 1 of 4. How do you express the number of comparisons?
Step 1 of 3. What is for and ?
tres_vias(a, lo, hi, p): rearrange a[lo..hi] in place (both endpoints included) into three contiguous blocks < p, == p and > p, and return (m, M) with the equal elements in a[m..M] (if none are equal, M = m - 1). Use only < and > comparisons between elements (no sorting) and make one pass: when all keys are equal, the cost must be linear. Do not touch elements outside lo..hi.def tres_vias(a, lo, hi, p):
"""Particiona a[lo..hi] en < p | == p | > p. Devuelve (m, M): los iguales ocupan a[m..M]."""
# invariante sugerido: a[lo..m-1] < p, a[m..i-1] == p, a[i..M] sin examinar, a[M+1..hi] > p
return lo, hiMore than one answer may be correct.
a[j] < p). How many comparisons does it make?sorted (and list.sort) in CPython is correct?Summary
- Hoare partitioning makes about three times fewer swaps than Lomuto and handles repeated keys well; Dijkstra’s three-way partition sets them aside in one pass and yields cost with the frequency entropy.
- Any deterministic quicksort choosing a pivot from a constant-size sample has an input costing , constructed by running it against an adversarial comparator (McIlroy). Median of three does not prevent this; a random pivot protects only if the seed is unpredictable.
- Pair analysis is the technique: , linearity of expectation does the rest, and recursion depth is with probability by Chernoff.
- Quickselect recurses on one side: expected cost (exactly for the median). Median of medians with groups of 5 satisfies , linear because ; with groups of 3 the sum is 1 and the analysis does not yield linear time.
- Las Vegas: always correct, random time. Monte Carlo: fixed time, bounded error. Stopping and returning an arbitrary answer converts the former to the latter using Markov; verifying and retrying converts Monte Carlo to Las Vegas.
- Production sorts are hybrids: introsort (median of three, depth fallback to heapsort, insertion sort for small ranges), pdqsort (also breaks patterns and detects duplicates) and, in Python, an adaptive stable mergesort (Timsort with powersort merge policy).
numpy.partitionis introselect.