Module contents
Lesson 4 of 33Core 100 min

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 Θ(n2)\Theta(n^2). This is not merely theoretical: choosing the first element as pivot makes already sorted input, a common case, cost n(n−1)/2n(n-1)/2 comparisons. How did such an algorithm become standard? The answer has three pieces recurring throughout the module:

  1. 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 2nln⁡n2n\ln n for every input and follows in four lines using indicator variables.
  2. Select without sorting. Finding the kkth 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.
  3. 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 log⁡2n!\log_2 n! is our benchmark.

Partitioning: Lomuto and Hoare

The algorithm rests on one operation. Given pivot pp and segment a[lo..hi]a[lo..hi], partitioning rearranges the segment so elements below pp 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 a[lo..i−1]a[lo..i-1] are below pp and those of a[i..j−1]a[i..j-1] are at least as large. On loop exit, swapping a[i]a[i] with the pivot puts it in its final position. It makes exactly n−1n-1 comparisons for a segment of nn elements and, on a random permutation, about n/2n/2 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 n/6n/6 swaps per partition versus Lomuto’s n/2n/2. The code below gives ≈0.34 nln⁡n\approx 0.34\,n\ln n versus ≈0.91 nln⁡n\approx 0.91\,n\ln n 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 [lo..j][lo..j] and [j+1..hi][j+1..hi], since the pivot need not end at jj, and the pivot must be a[lo]a[lo], not a[hi]a[hi], 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, T(n)=T(n−1)+n−1T(n) = T(n-1) + n - 1 whenever the pivot always falls at an extreme, and the recurrence yields T(n)=n(n−1)/2T(n) = n(n-1)/2. 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 O(nlog⁡n)\bigO(n\log n), 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 nn 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 ss sampled elements in each subproblem are among its ss smallest, leaving almost everything on one side of the pivot. Each partition discards O(s)\bigO(s) elements, requiring Ω(n/s)\Omega(n/s) 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 O(nlog⁡n)\bigO(n\log n) in the worst case, though too slow in practice. The figure constructs adversarial inputs for three pivot rules.

InteractiveThe pivot adversary
Input: position (horizontal axis) and value (vertical)
color = depth at which each element is fixed:0 to 65
Comparisons versus nn (logarithmic axes)
  • sorted
  • random
  • adversarial
  • n²/2
  • 2n ln n
Algorithm
Pivot rule
Input
128
Comparisons4 918
Ratio to n2/2n^2/20.60
Reference 2nln⁡n2n\ln n1 242
Recursion depth65
This input makes the algorithm quadratic: 0.60 times n2/2n^2/2 and recursion depth 65.
Quicksort with Hoare partitioning and three pivot rules. With «Adversaria», McIlroy's generator constructs input by comparison; the first chart plots position versus value colored by the depth at which each element is fixed. The second plots comparisons versus nn on logarithmic axes: slope 2 is quadratic and slope near 1 is nlog⁡nn\log n. Try three cases. (1) For a first-element pivot, sorted input is already adversarial. (2) Median-of-three fixes sorted input, but the adversarial input still has quadratic cost and depth ≈n/2\approx n/2. (3) With a random pivot, input constructed against one seed is ordinary for another and only works when «El atacante conoce la semilla» is enabled.

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 CC counts comparisons, we want E[C]\E[C]. Solving recurrence T(n)=n−1+1n∑k(T(k)+T(n−1−k))T(n) = n - 1 + \frac{1}{n}\sum_{k}(T(k) + T(n-1-k)) works via generating functions and also gives variance. A clearer method, used throughout this module’s randomized algorithms, counts pairs.

Label elements by rank z1<z2<⋯<znz_1 < z_2 < \dots < z_n, assuming distinct values for now. Pair (zi,zj)(z_i, z_j) 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

InteractiveWho gets compared with whom?
  • pivot
  • smaller
  • larger
  • compared
Finished: 47 comparisons (41.5 expected).
1234567891011121314
11223344556677889910101111121213131414
Top right: compared pairs. Bottom left: 2/(j−i+1)2/(j-i+1).
  • theory 2/(d+1)
  • this run
step 67 / 67
Experiment
Input
Size
14
Comparisons so far47 of 47
Expected 2(n+1)Hn−4n2(n+1)H_n - 4n41.5
Approximation 2nln⁡n2n\ln n73.9
Hover over the matrix: each cell is a pair of values (i,j)(i, j).
Randomized quicksort on values 11 through nn. Each comparison lights cell (i,j)(i, j) in the upper-right matrix; the lower triangle shows theoretical probability 2/(j−i+1)2/(j-i+1). Play one run: adjacent values are always compared, distant ones rarely. Switch to «Muchas ejecuciones» and increase repetitions: each cell's observed frequency approaches the formula, and the line chart averaging diagonals approaches 2/(d+1)2/(d+1). Change input to sorted or reversed: does anything change?

Cells next to the diagonal are the first to inspect: (i,i+1)(i, i+1) 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 Zij={zi,zi+1,…,zj}Z_{ij} = \{z_i, z_{i+1}, \dots, z_j\}, containing j−i+1j - i + 1 elements. Pivot q∉Zijq \notin Z_{ij} puts all of ZijZ_{ij} on one side: if q<ziq < z_i they are all greater, and if q>zjq > z_j all smaller. Until a pivot from ZijZ_{ij} is chosen, the j−i+1j - i + 1 elements remain in one subproblem. Let PP be the first element of ZijZ_{ij} chosen as pivot. At that point all of ZijZ_{ij} is in the subproblem, whose pivot is uniform; conditioned on falling in ZijZ_{ij}, it is uniform on ZijZ_{ij}. Each of its j−i+1j - i + 1 elements is PP with probability 1/(j−i+1)1/(j-i+1) regardless of previous history.

  • If P∈{zi,zj}P \in \{z_i, z_j\}, the pivot is compared with every other subproblem element, including the other endpoint: ziz_i and zjz_j are compared.
  • If P=zkP = z_k with i<k<ji < k < j, then zi<zk<zjz_i < z_k < z_j and the pivot sends them to different sides. They never share a subproblem or get compared. Before PP they were not compared either, since comparing ziz_i with zjz_j requires one to be pivot.

The two endpoints are two of j−i+1j-i+1 equally likely cases, giving probability 2/(j−i+1)2/(j-i+1).

∎

This is indicator random-variable analysis. Let Xij=1[zi y zj se comparan]X_{ij} = \ind[z_i \text{ y } z_j \text{ se comparan}]. The comparison count is C=∑i<jXijC = \sum_{i<j} X_{ij}. By linearity of expectation, without requiring independence, absent here because the XijX_{ij} are highly correlated,

E[C]=∑i<jE[Xij]=∑i<j2j−i+1=∑d=1n−12(n−d)d+1=2∑k=2nn+1−kk=2(n+1)(Hn−1)−2(n−1).\E[C] = \sum_{i<j} \E[X_{ij}] = \sum_{i<j} \frac{2}{j-i+1} = \sum_{d=1}^{n-1} \frac{2(n-d)}{d+1} = 2\sum_{k=2}^{n} \frac{n+1-k}{k} = 2(n+1)(H_n - 1) - 2(n-1) .

Group pairs by distance d=j−id = j - i, with n−dn - d at each dd, change k=d+1k = d + 1 and separate (n+1)/k−1(n+1)/k - 1. Simplifying with harmonic number Hn=∑k=1n1/kH_n = \sum_{k=1}^{n} 1/k:

E[C]=2(n+1)Hn−4n=2nln⁡n−(4−2γ) n+2ln⁡n+O(1)≈2nln⁡n−2.85 n,\boxed{\E[C] = 2(n+1)H_n - 4n = 2n\ln n - (4 - 2\gamma)\,n + 2\ln n + \bigO(1) \approx 2n\ln n - 2.85\,n},

where γ≈0.5772\gamma \approx 0.5772 is Euler’s constant. Check n=3n = 3: pairs (1,2)(1,2) and (2,3)(2,3) have probability 1, and (1,3)(1,3) has 2/32/3, so E[C]=8/3\E[C] = 8/3 and the formula gives 2⋅4⋅116−12=832 \cdot 4 \cdot \tfrac{11}{6} - 12 = \tfrac{8}{3}.

This holds for every input: expectation is over the algorithm’s coins alone. Compare with the lower bound log⁡2n!=nlog⁡2n−1.44 n+O(log⁡n)\log_2 n! = n\log_2 n - 1.44\,n + \bigO(\log n): the ratio of E[C]\E[C] to log⁡2n!\log_2 n! tends to 2ln⁡2≈1.3862\ln 2 \approx 1.386. 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 n=1000n = 1000, E[C]=10985.9\E[C] = 10985.9 versus log⁡21000!=8529.4\log_2 1000! = 8529.4 gives ratio 1.29, still below the limit.

Expectation is not a guarantee: high probability

An expectation of 2nln⁡n2n\ln n does not say how likely a bad run is. The standard deviation of CC is known to grow like ≈0.65 n\approx 0.65\,n, small compared with the mean 2nln⁡n2n\ln n (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 O(log⁡n)\bigO(\log n) with probability 1−1/nc1 - 1/n^{c}.

Proof

Fix an element xx and consider the chain of subproblems containing it, of sizes m0=n≥m1≥…m_0 = n \ge m_1 \ge \dots Call the pivot choice for a subproblem of size m≥2m \ge 2 good if both resulting sides have size at most 3m/43m/4. This happens if the pivot rank rr satisfies r−1≤3m/4r - 1 \le 3m/4 and m−r≤3m/4m - r \le 3m/4, that is, r∈[m/4, 3m/4+1]r \in [m/4,\ 3m/4 + 1]: a closed interval of length m/2+1m/2 + 1 containing at least ⌊m/2⌋+1>m/2\lfloor m/2 \rfloor + 1 > m/2 integers. Thus, conditioned on the entire preceding history, each choice is good with probability at least 1/21/2.

Each good choice multiplies the size by at most 3/43/4. Since sizes are integers and xx remains in the subproblem, there can be at most L=⌈log⁡4/3n⌉L = \lceil\log_{4/3} n\rceil good choices in the chain for xx. Therefore, if the chain for xx has more than D=8LD = 8L levels, among the first DD at most LL are good. The number of good choices in DD attempts stochastically dominates a Bin(D,1/2)\mathrm{Bin}(D, 1/2), with mean μ=D/2=4L\mu = D/2 = 4L. Using the multiplicative Chernoff bound P[X≤(1−δ)μ]≤e−δ2μ/2\Pr[X \le (1-\delta)\mu] \le e^{-\delta^2\mu/2} and δ=3/4\delta = 3/4 (because L=(1−34)μL = (1 - \tfrac34)\mu):

P[profundidad de x>8L]≤P[Bin(D,12)≤L]≤e−916⋅4L2=e−9L/8≤n−98ln⁡(4/3)≤n−3.9.\Pr[\text{profundidad de } x > 8L] \le \Pr[\mathrm{Bin}(D, \tfrac12) \le L] \le e^{-\frac{9}{16}\cdot\frac{4L}{2}} = e^{-9L/8} \le n^{-\frac{9}{8\ln(4/3)}} \le n^{-3.9}.

By the union bound over the nn elements, the probability that any exceeds that depth is at most n−2.9≤n−2n^{-2.9} \le n^{-2}. Since each recursion level makes at most nn comparisons in total, the cost is ≤8n⌈log⁡4/3n⌉\le 8n\lceil\log_{4/3} n\rceil with that probability.

∎

The constant is very generous (with a random pivot and n=512n = 512, the adversary figure shows a depth of 18 to 23 depending on the input, while the bound is 8⌈log⁡4/3512⌉=1768\lceil\log_{4/3} 512\rceil = 176); what matters is its form: the probability of exceeding clog⁡nc\log n decays as a power of nn 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 2nln⁡n2n\ln n, 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 Θ(n2)\Theta(n^2) 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, a[lo..m−1]<pa[lo..m-1] < p, a[m..i−1]=pa[m..i-1] = p, a[i..M]a[i..M] are unexamined, and a[M+1..hi]>pa[M+1..hi] > p.

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 a[i..M]a[i..M] loses one, so there are exactly hi−lo+1hi - lo + 1 iterations: linear cost for any contents, and nn when all keys are equal (in one pass, without recursion). With kk distinct values, the same pair argument, now weighted, gives expected cost of order n(1+H)n(1 + H), where HH is the Shannon entropy (in bits) of key frequencies. This result of Sedgewick and Bentley, which we will not prove, says that with kk equally likely keys, the cost is O(nlog⁡k)\bigO(n\log k) instead of O(nlog⁡n)\bigO(n\log n). 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 kk largest values (the kk best candidates from a language model, the top-kk case you saw with argpartition in the tools module). Selection: given an array of nn elements and a kk, return the kk-th smallest. Sorting solves the problem in O(nlog⁡n)\bigO(n\log n), but seems wasteful: must we sort elements far from kk?

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 rr, either r=kr = k and we are done, or the kk-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 T(n)T(n) be the maximum expected number of comparisons over all inputs of size at most nn and all kk; defined this way, TT is nondecreasing. Partitioning costs n−1n - 1 and the pivot has rank rr uniformly distributed in {1,…,n}\{1, \dots, n\}; in the worst case (for kk) we continue on the larger side, of size max⁡(r−1,n−r)\max(r - 1, n - r). Each value mm between ⌊n/2⌋\lfloor n/2\rfloor and n−1n-1 appears at most twice:

T(n)≤n−1+1n∑r=1nT(max⁡(r−1, n−r))≤n+2n∑m=⌊n/2⌋n−1T(m).T(n) \le n - 1 + \frac{1}{n}\sum_{r=1}^{n} T\big(\max(r-1,\,n-r)\big) \le n + \frac{2}{n}\sum_{m=\lfloor n/2\rfloor}^{n-1} T(m).

Assume inductively T(m)≤cmT(m) \le cm for m<nm < n. Since ∑m=⌊n/2⌋n−1m≤38n2\sum_{m=\lfloor n/2\rfloor}^{n-1} m \le \tfrac{3}{8}n^2 (checked separately for even and odd nn), we obtain

T(n)≤n+2cn⋅3n28=n+3c4 n≤cnsi c≥4.T(n) \le n + \frac{2c}{n}\cdot\frac{3n^2}{8} = n + \frac{3c}{4}\,n \le cn \quad\text{si } c \ge 4.

The induction starts with T(1)=0T(1) = 0, and T(n)≤4nT(n) \le 4n.

∎

The 4 is a loose induction bound, not the actual value. The exact calculation (a classic result in Knuth) gives, for the kk-th element, 2((n+1)Hn−(n+3−k)Hn+1−k−(k+2)Hk+n+3)2\big((n+1)H_n - (n+3-k)H_{n+1-k} - (k+2)H_k + n + 3\big) expected comparisons, which for large nn and kk is 2n+2kln⁡(n/k)+2(n−k)ln⁡(n/(n−k))+O(log⁡n)2n + 2k\ln(n/k) + 2(n-k)\ln\big(n/(n-k)\big) + \bigO(\log n), maximized at the median: 2n(1+ln⁡2)≈3.39 n2n(1 + \ln 2) \approx 3.39\,n. Compared with the 2nln⁡n2n\ln n for sorting, at n=106n = 10^6 these are 3.4×1063.4\times 10^6 versus 2.8×1072.8\times 10^7. This is the algorithm behind numpy.partition, std::nth_element and any “unsorted top-kk” (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 8n8n), 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 xx is the median of the row of medians. Everything below and to the left of xx is smaller: columns to its left have median less than xx, and within each, its two smallest elements are smaller than its median. Similarly, everything above and to the right is larger.

InteractiveThe median-of-medians grid
  • less than pivot (guaranteed)
  • greater than pivot (guaranteed)
  • pivot: median of medians
  • not guaranteed
med.largersmaller259253118122434611152043714174145410233944192226374016212832351318293038327333642each column is a sorted group of 5; columns are sorted by median →
Recurrence T(n)≤T(n/g)+T(αn)+O(n)T(n) \le T(n/g) + T(\alpha n) + O(n): coefficient sum 1/g+α1/g + \alpha
g = 3
1.00
g = 5
0.90
g = 7
0.86
g = 9
0.83
With groups of 5: α=14/20≈0.70\alpha = 14/20 \approx 0.70 and the sum 1/g+α1/g + \alpha is 0.90, less than 1: the total cost is linear, Θ(n)\Theta(n).
Groups
Group size
9
Data
Elements nn45
Guaranteed smaller14 (31.1 %)
Guaranteed larger14 (31.1 %)
Bound (g+1)/(4g)(g+1)/(4g)30.0 %
Recursion on at most30 (66.7 %)
Actual pivot rank23 of 45
Each column is a sorted group, and columns are sorted by median; the pivot (orange) is the median of the medians. Blue elements are smaller than the pivot by construction; red ones are larger. Gray elements have no guarantee: enable «Mostrar el orden real» to see that each falls on one side or the other depending on the data. With groups of 5 the guaranteed region on each side is about 3n/103n/10. Switch to 3 and 7: below, the sum of coefficients 1/g+α1/g + \alpha in the recurrence T(n)≤T(n/g)+T(αn)+O(n)T(n) \le T(n/g) + T(\alpha n) + O(n) determines the cost: less than 1 is linear. What happens exactly when g=3g = 3?

Counting n=5cn = 5c elements (cc groups), the guaranteed region on each side has, including the pivot itself, 3⌈c/2⌉≥3n/103\lceil c/2\rceil \ge 3n/10 elements: three from each of the ⌈c/2⌉\lceil c/2 \rceil 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 gg, the guaranteed fraction is g+14g\frac{g+1}{4g} and what remains after partitioning is at most α=3g−14g\alpha = \frac{3g-1}{4g}: with g=5g = 5, α=7/10\alpha = 7/10.

So the algorithm calls itself twice: once on n/5n/5 elements for the pivot, and once on at most 7n/107n/10 (plus a constant) for the result, performing linear work (sorting groups of 5 and partitioning):

T(n)≤T(⌈n/5⌉)+T(7n/10+6)+an.T(n) \le T(\lceil n/5\rceil) + T(7n/10 + 6) + an.
Proof

By substitution. For n<140n < 140 the cost is constant per element, so choose cc large enough for T(n)≤cnT(n) \le cn to hold in those cases; assume T(m)≤cmT(m) \le cm for m<nm < n, with n≥140n \ge 140. Then

T(n)≤c(n5+1)+c(7n10+6)+an=cn+(−cn10+7c+an).T(n) \le c\left(\tfrac{n}{5} + 1\right) + c\left(\tfrac{7n}{10} + 6\right) + an = cn + \Big(-\tfrac{cn}{10} + 7c + an\Big).

For n≥140n \ge 140 we have 7c≤cn/207c \le cn/20, so the expression in parentheses is at most −cn/20+an≤0-cn/20 + an \le 0 if c≥20ac \ge 20a. Thus T(n)≤cnT(n) \le cn. The 140140 is not magic: it is what is needed to absorb the constants +1+1 and +6+6 in the recurrence.

∎

With the Akra–Bazzi theorem the calculation takes one line: T(n)=T(n/5)+T(7n/10)+Θ(n)T(n) = T(n/5) + T(7n/10) + \Theta(n) satisfies (1/5)p+(7/10)p=1(1/5)^p + (7/10)^p = 1 for p≈0.84<1p \approx 0.84 < 1, and then T(n)=Θ(np(1+∫1nu−p du))=Θ(n)T(n) = \Theta\big(n^p(1 + \int_1^n u^{-p}\,du)\big) = \Theta(n). Group size matters. With groups of 7, p≈0.76p \approx 0.76; with groups of 9, p≈0.72p \approx 0.72: larger groups are further into the linear regime, but sorting them costs more per element. With groups of 3, α=2/3\alpha = 2/3 and the two coefficients sum to 1/3+2/3=11/3 + 2/3 = 1: p=1p = 1 and the integral contributes ln⁡n\ln n. The standard analysis therefore gives O(nlog⁡n)\bigO(n\log n), 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 nn comparisons versus 3.4 n3.4\,n 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.

AlgorithmClassWhat is randomError
Randomized quicksortLas VegasTimeNone
QuickselectLas VegasTimeNone
Hashing with retries (choose hh until there are no collisions)Las VegasNumber of attemptsNone
Miller–Rabin testMonte Carlo, one-sidedAnswer“Composite” is always correct; “probably prime” fails with probability ≤1/4\le 1/4 per base
Freivalds (check AB=C\mat{A}\mat{B} = \mat{C})Monte Carlo, one-sidedAnswer“Different” is always correct; “equal” fails with probability ≤1/2\le 1/2 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 E[T]\E[T], run it for at most t E[T]t\,\E[T] steps and, if it has not finished, return an arbitrary answer. By Markov’s inequality, P[T≥t E[T]]≤1/t\Pr[T \ge t\,\E[T]] \le 1/t: you have obtained a fixed-time Monte Carlo algorithm with error ≤1/t\le 1/t.
  • Monte Carlo to Las Vegas: verify and retry. If there is a fast answer verifier, repeat Monte Carlo until the verifier accepts. With error δ<1\delta < 1 per attempt, the number of attempts is geometric, with expectation 1/(1−δ)1/(1-\delta), 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 ≥1/2\ge 1/2 (Markov), so the number of attempts is bounded by a geometric variable with mean 2 and total expected cost does not exceed 2⋅2 E[T]2 \cdot 2\,\E[T]. 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 2⌊log⁡2n⌋2\lfloor\log_2 n\rfloor, abandons that subproblem and sorts it with heapsort, which has worst case O(nlog⁡n)\bigO(n\log n) 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 O(nlog⁡n)\bigO(n\log n) 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 log⁡n\log n 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 O(n)\bigO(n) 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 n H+2nn\,\mathcal{H} + 2n, where H\mathcal{H} is the entropy (in bits) of relative run lengths: nearly optimal for those lengths. This explains why an already sorted array costs n−1n - 1 comparisons and why two or three long runs cost little more: you will see this in the code.

AlgorithmWorst caseExtra memoryStableWhere
Randomized quicksortO(n2)\bigO(n^2) (negligible probability); expected 2nln⁡n2n\ln nO(log⁡n)\bigO(\log n) expectedNoTeaching, basis for others
IntrosortO(nlog⁡n)\bigO(n\log n)O(log⁡n)\bigO(\log n)Nostd::sort, np.sort
pdqsortO(nlog⁡n)\bigO(n\log n); O(n)\bigO(n) with patternsO(log⁡n)\bigO(\log n)NoGo, Rust (earlier versions)
Timsort / powersortO(nlog⁡n)\bigO(n\log n); O(n)\bigO(n) with runsO(n)\bigO(n)Yessorted and list.sort (CPython), Java object sort
HeapsortO(nlog⁡n)\bigO(n\log n)O(1)\bigO(1)NoFallback 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 2(n+1)Hn−4n2(n+1)H_n - 4n, how many swaps Hoare saves, and what happens with repeated keys. (In three-way partitioning we count one three-outcome comparison per element.)

[ ]Lomuto, Hoare and three-way partitioning: cost and repeated keysBrowser
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, 1 124 2501\,124\,250 of 1 125 0001\,125\,000 possible), while Hoare barely notices and three-way partitioning costs exactly nn. 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.

[ ]Miniature introsort versus McIlroy's adversaryBrowser
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 n2/2n^2/2 (125 613125\,613 comparisons versus 125 000125\,000). With the depth fallback, the algorithm detects something wrong at 2⌊log⁡2n⌋2\lfloor\log_2 n\rfloor levels, falls back to heapsort on the remaining subproblem, and cost drops to about five times nlog⁡2nn\log_2 n (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.

[ ]Quickselect, median of medians and the cost tailBrowser
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 nn for the median), the distribution is narrow with a short right tail (less than 2% of runs exceed 6n6n and none reaches 8n8n), far below Markov’s 50% bound, and median of medians costs on the order of 5 to 8 nn but does not degrade on sorted input, where fixed-pivot quickselect sinks to n2/2n^2/2. 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 n−1n-1, eight sorted runs cost about 4n4n and random input comes within 1.3% of the lower bound log⁡2n!\log_2 n!. In NumPy, np.partition and np.argpartition implement selection (introselect), with the guarantees you already know.

[ ]Python sorted (powersort) and numpy.partitionBrowser
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-kk recipe in the last line (partition and then sorting only the kk selected elements) costs O(n+klog⁡k)\bigO(n + k\log k) instead of O(nlog⁡n)\bigO(n\log n): this is the idea used by decoders sampling from a vocabulary of tens of thousands of tokens with top-kk, and the same idea you saw with argpartition in the tools module.

Common mistakes

Exercises

ProofExpected number of comparisons
Prove: For randomized quicksort on nn distinct elements, E[C]=2(n+1)Hn−4n\E[C] = 2(n+1)H_n - 4n, where Hn=∑k=1n1/kH_n = \sum_{k=1}^n 1/k.
0
Let z1<⋯<znz_1 < \dots < z_n be the sorted elements and XijX_{ij} the indicator that ziz_i and zjz_j are ever compared.

Step 1 of 4. How do you express the number of comparisons?

NumericExpected comparisons for n = 1000
Calculate the expected number of comparisons of randomized quicksort for n=1000n = 1000 distinct elements, using the exact formula 2(n+1)Hn−4n2(n+1)H_n - 4n (use H1000=7.485470861H_{1000} = 7.485470861). Round to the nearest integer.
NumericAre ranks 10 and 30 compared?
In randomized quicksort on n=100n = 100 distinct elements, what is the probability that the elements of ranks 10 and 30 are compared? Answer as a decimal.
ProofGroups of 5 work; groups of 3 do not
Prove: Median of medians with groups of 5 is O(n)\bigO(n) in the worst case, whereas the same analysis with groups of 3 gives only O(nlog⁡n)\bigO(n\log n).
0
For odd group size gg, the fraction guaranteed smaller (and larger) than the pivot approaches (g+1)/(4g)(g+1)/(4g), so selection recurses on at most αn\alpha n with α=(3g−1)/(4g)\alpha = (3g-1)/(4g), and T(n)≤T(n/g)+T(αn)+anT(n) \le T(n/g) + T(\alpha n) + an.

Step 1 of 3. What is α\alpha for g=5g = 5 and g=3g = 3?

NumericRemaining fraction with groups of 7
In median of medians with groups of size g=7g = 7, what fraction of elements can remain at most, in the limit, in the main recursive subproblem? Answer as a decimal.
NumericStop and restart quickselect
Quickselect has expected cost E[T]≤4n\E[T] \le 4n. Run it with a limit of 8n8n comparisons and, if it has not finished, restart from scratch with fresh random choices. Using Markov's inequality and the mean number of attempts, what constant cc bounds total expected cost by c nc\,n? Use the bound from 8n×(intentos medios)8n \times (\text{intentos medios}).
CodeDijkstra's three-way partition
Implement 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, hi
Shift+Enter to run
QuizLas Vegas or Monte Carlo
Which of these randomized algorithms are Las Vegas (always correct, random time)?

More than one answer may be correct.

QuizLomuto with repeated keys
You sort an array of nn zeros using Lomuto quicksort (random pivot, strict comparison a[j] < p). How many comparisons does it make?
QuizMedian of three and the adversary
A service uses deterministic quicksort with a median-of-three pivot to sort data sent by clients. Which statement is correct?
QuizHow does sorted sort?
Which statement about sorted (and list.sort) in CPython is correct?

Summary

Key idea
Randomizing the pivot turns a data-dependent worst case into bad luck depending on the algorithm’s random choices: randomized quicksort makes 2(n+1)Hn−4n≈2nln⁡n2(n+1)H_n - 4n \approx 2n\ln n expected comparisons for every input, and the same principle yields expected linear-time selection (quickselect), which becomes linear in the worst case with a guaranteed pivot choice (median of medians).
  • 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 O(n(1+H))\bigO(n(1 + H)) with HH the frequency entropy.
  • Any deterministic quicksort choosing a pivot from a constant-size sample has an input costing Θ(n2)\Theta(n^2), 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: P[zi y zj se comparan]=2/(j−i+1)\Pr[z_i \text{ y } z_j \text{ se comparan}] = 2/(j-i+1), linearity of expectation does the rest, and recursion depth is O(log⁡n)\bigO(\log n) with probability 1−1/n21 - 1/n^2 by Chernoff.
  • Quickselect recurses on one side: expected cost ≤4n\le 4n (exactly ≈3.39 n\approx 3.39\,n for the median). Median of medians with groups of 5 satisfies T(n)≤T(n/5)+T(7n/10)+O(n)T(n) \le T(n/5) + T(7n/10) + \bigO(n), linear because 1/5+7/10<11/5 + 7/10 < 1; 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.partition is introselect.