Expected Running Time and Randomized Analysis
Consider hiring a randomized algorithm that shuffles its own input before working. Randomized quicksort is one such example. On any fixed input, the running time is no longer a single number. Instead, it becomes a random variable. This happens because it depends on coin flips the algorithm itself makes. The natural question shifts. It moves from "how long does this take?" to "how long does this take on average?" This average is taken over all possible coin flips. This is the domain of expected running time analysis. It is one of the most powerful tools in the algorithm designer's toolkit. The idea matters because many of the fastest, simplest algorithms are randomized. They are also among the most widely deployed. Quicksort's average-case behavior underlies sorting routines in standard libraries. Randomized hashing defeats adversarial inputs in web servers and compilers. Randomized min-cut and primality testing algorithms are staples of network analysis and cryptography. In every one of these cases, a worst-case analysis alone would be too pessimistic. Alternatively, it would require assumptions about input distributions that real systems cannot guarantee. Randomization sidesteps this problem. It makes the algorithm's own coin flips the source of randomness. Expectation is taken over those coin flips for every fixed input. This is a subtly different guarantee than assuming a random input. It is also much more robust. The big picture is this: we might average over random inputs, as in classical average-case analysis. Or we might average over the algorithm's internal random choices, as in randomized analysis. Either way, the mathematical machinery is the same. It relies on random variables, linearity of expectation, and especially indicator random variables. Indicator variables convert an awkward combinatorial counting problem into something simpler. That problem asks: "how many total comparisons happen across all possible executions?" It becomes a sum of simple 0/1 events. The individual probabilities of these events are easy to compute. This transformation is arguably the single most important technique. It helps tame complexity in probabilistic algorithm analysis. This article builds the formal apparatus for expected running time analysis. We cover what expectation over an algorithm's random choices means. We show how indicator random variables reduce global counting to local probability calculations. We explain how linearity of expectation lets us add these local pieces. Notably, this works without needing independence. We work a complete derivation of randomized quicksort's expected time. We trace a small example by hand. We also catalog the classic mistakes analysts make. These mistakes occur when they conflate average-case and randomized guarantees.
- Expected running time treats an algorithm's own random choices — not the input — as the source of randomness, giving a guarantee that holds for every fixed input.
- The key device is the indicator random variable: if event occurs, else , so .
- Linearity of expectation, , holds unconditionally — no independence between the required.
- Randomized quicksort achieves expected comparisons on every input, by summing pairwise-comparison probabilities over all element pairs.
- Randomized analysis differs from classical average-case analysis: the former assumes a uniform random input, the latter assumes uniform random choices made by the algorithm regardless of input.
- The technique generalizes far beyond sorting: hashing, randomized selection, skip lists, and randomized graph algorithms all rely on the same indicator-variable + linearity machinery.
Expected running time is computed by decomposing total work into indicator random variables for elementary events, then summing their probabilities via linearity of expectation — without ever needing those events to be independent.
The idea
An algorithm's running time is normally treated as a deterministic function of input size, or — after the ideas in Best, Average, and Worst Case Analysis — as a function that varies with the particular input of size . Randomized analysis introduces a third source of variability: the algorithm itself flips coins, so even on a single, fixed input, running time is a random variable whose randomness comes entirely from those internal coin flips. The expected running time is , the average of weighted by the probability of each sequence of coin flips. This distinction is crucial and frequently blurred. Average-case analysis (studied for deterministic algorithms) assumes a probability distribution over inputs — e.g., "assume all permutations are equally likely" — and is only meaningful if that assumption about the world actually holds. Randomized analysis makes no assumption about the input at all; the input can be chosen by a worst-case adversary who knows the algorithm's code. The randomness comes from the algorithm's own random number generator, which the adversary cannot predict in advance. The statement "randomized quicksort runs in expected time" is therefore a guarantee for every input array, not merely for a "typical" one. This makes randomized bounds strictly more robust than average-case bounds computed under an input distribution assumption, and it is why randomization is prized in adversarial settings such as network routing, hash table design in public-facing servers, and cryptographic protocols. The workhorse for computing is the indicator random variable. For an event in a sample space, define
A one-line but load-bearing fact: , since . Many running-time quantities — total number of comparisons, total number of swaps, total probes in a hash table — can be written as a sum of indicator variables, one per elementary event (e.g., one per candidate pair of elements, one per attempted probe). Then linearity of expectation,
lets us compute the expectation of the sum by adding up the individual, easy-to-compute probabilities — crucially, even when the are statistically dependent on each other. This last point is what makes the technique so powerful: proving independence between events is often hard or false, but linearity of expectation needs no such proof.
How it works
The general recipe for bounding an expected running time has four steps. 1. Identify the elementary cost unit. Pick the dominant operation (comparisons for sorting, probes for hashing, edge relaxations for graph algorithms) so that total running time is proportional to the count of this unit, up to lower-order terms. 2. Express the total count as a sum of indicators. Enumerate a family of events (often "pair triggers the operation") and define so that the total count . 3. Compute for each event, usually via a clean combinatorial or probabilistic argument that does not require knowing anything about the other events. 4. Sum via linearity: , then bound this sum (often by comparison to a harmonic series or a geometric series) to get a closed form such as . We instantiate this recipe fully for randomized quicksort, the canonical example.
Randomized quicksort
Randomized quicksort chooses the pivot for each partition uniformly at random from the current subarray, independent of everything else. This single change converts quicksort's dreaded worst case (triggered by already-sorted input under a fixed pivot rule) into an expected case on every input. ``` RANDOMIZED-QUICKSORT(A, low, high): if low < high: p = RANDOM-INTEGER(low, high) # uniform pivot index swap A[p] and A[high] pivot = A[high] i = low - 1 for j = low to high - 1: if A[j] <= pivot: i = i + 1 swap A[i] and A[j] swap A[i+1] and A[high] q = i + 1 # final pivot position RANDOMIZED-QUICKSORT(A, low, q - 1) RANDOMIZED-QUICKSORT(A, q + 1, high) ``` Let the input, after relabeling, be the sorted sequence of ranks (any fixed array's elements can be relabeled by rank without changing the comparison structure). Define, for :
The total number of comparisons performed by the algorithm is exactly
because quicksort compares any two elements at most once (once a pivot is chosen, it is compared against everything else in its subarray and never touched again).
Key probability computation. Consider with , and the set of all elements between them (inclusive), of size . Two facts:
- and are compared if and only if one of them is chosen as a pivot before any other element of is chosen as a pivot. (If some element strictly between them is pivoted first, and end up in different subarrays and are never compared again.)
- Because pivots are chosen uniformly at random and independently at each recursive call, the relative order in which the elements of are first chosen as pivots (among calls that contain all of ) is a uniformly random permutation of .
Hence
By linearity of expectation (no independence between the needed):
Substitute (so ranges from to , and for each there are valid pairs ):
using the harmonic number bound . This gives the clean, famous result:
Complexity & correctness
Time complexity. The derivation above shows for randomized quicksort, on any input array — including already-sorted or adversarially constructed arrays. All other work (partitioning overhead, recursive call bookkeeping) is proportional to the number of comparisons plus per level of recursion, so the total expected running time is as well. This should be contrasted with:
- Worst case (over both input and coin flips): still , achieved if the random pivot happens to be the minimum or maximum element at every level — an event of vanishingly small but nonzero probability.
- Best case: , when pivots repeatedly split the array evenly.
- Expected case (this article's subject): for every fixed input, because the worst case has probability that decays exponentially in and contributes negligibly to the expectation.
Space complexity. Expected recursion depth is (by a similar indicator/probabilistic argument on the size of subproblems shrinking geometrically in expectation), giving expected auxiliary stack space; a bad sequence of pivots can still cause depth, so implementations often recurse on the smaller partition first and iterate on the larger one to guarantee worst-case space.
Correctness of the analysis (proof sketch). Two facts underpin the whole argument and deserve to be stated as an explicit invariant: 1. At most one comparison per pair. Quicksort's partitioning step compares every non-pivot element in a subarray to the pivot exactly once, and once an element is compared to a pivot it is placed in a side (left/right) that never merges with the other side again. Hence any two elements are compared at most once, across the whole execution. This is what licenses writing total comparisons as with no double-counting. 2. The "first pivoted wins" characterization is exact, not approximate. If neither nor is the first pivot chosen among , some element strictly between them is pivoted first and permanently separates from into different recursive calls — they can never be compared afterward. Conversely if (or ) is the first of pivoted, it is compared directly against every other currently co-resident element of , including , during that partition step. This gives the iff characterization used above, and hence the exact probability (a uniformly random permutation places any one of elements first with equal probability , and we want either of two designated elements to be first). 3. Linearity needs no independence. The events are certainly not independent (e.g., knowing were compared changes the conditional structure of later comparisons), but holds regardless, because expectation of a sum is always the sum of expectations — this is a linear-algebra fact about the expectation operator, true unconditionally.
Honest tradeoffs. Randomized analysis gives an expectation guarantee, not a certainty: on any run there is a small probability of the pathological case. For applications demanding hard real-time guarantees, expectation bounds must be paired with concentration results (e.g., Chernoff-style tail bounds showing decays exponentially in ) or replaced by algorithms with deterministic worst-case bounds, such as introspective sort or heapsort, at some constant-factor cost in practice.
Worked example
Take the (already sorted, hence adversarial for naive quicksort) input array of size :
Ranks equal values here, so . We compute for all pairs and sum.
| pair | ||
|---|---|---|
| (1,2) | 2 | 1.000 |
| (1,3) | 3 | 0.667 |
| (1,4) | 4 | 0.500 |
| (1,5) | 5 | 0.400 |
| (2,3) | 2 | 1.000 |
| (2,4) | 3 | 0.667 |
| (2,5) | 4 | 0.500 |
| (3,4) | 2 | 1.000 |
| (3,5) | 3 | 0.667 |
| (4,5) | 2 | 1.000 |
Summing the right column: (approximately), so
for this sorted array — versus the worst-case comparisons a fixed always-pick-first-element quicksort would need on this same input (achieving its full regime), and versus the theoretical best case around comparisons for merge-sort-style optimal splitting scaled to this small n (small- constants make direct comparison approximate, but the qualitative point holds: randomization has converted a worst-case input into a moderate expected cost). To see the mechanism concretely, trace one possible random execution. Suppose the random pivot choices are: first call picks pivot index (value ), splitting into and ; then picks pivot (value , so no further split needed on that side after one comparison), and picks pivot (value relative to that subarray). Tallying comparisons in this run: partitioning around costs comparisons (comparing against pivot ); partitioning around costs comparison; partitioning around costs comparison. Total for this particular run: comparisons — below the expectation of , illustrating that expectation is an average over many possible coin-flip sequences, some cheaper, some (like always picking the min/max) far more expensive.
Common pitfalls & traps
| Pitfall | Why it's wrong | Fix |
|---|---|---|
| Confusing "expected running time" with "average-case over random inputs" | Randomized analysis makes no assumption about the input; average-case analysis assumes a distribution over inputs, which may not hold in practice | State clearly which randomness (input vs. algorithm coins) the expectation is over |
| Assuming indicator variables must be independent before applying linearity | Linearity of expectation holds for any random variables, dependent or not | Never invoke independence unless you need or variance bounds — for expectation of a sum, skip the issue entirely |
| Treating "expected " as a guarantee that no run is ever slow | Expectation is an average; a run is possible (e.g., always picking the min pivot), just very improbable | Pair expectation bounds with tail/concentration arguments when worst-run guarantees matter |
| Double-counting comparisons when defining events | If the algorithm could compare a pair multiple times, summing indicators over pairs undercounts or overcounts total work | Verify (as done above) that each pair is compared at most once before writing total cost as |
| Forgetting the randomness must come from the algorithm, not a fixed pivot rule | "Randomized quicksort" without genuine per-call random pivot choice reduces to ordinary quicksort with the same adversarial worst case | Ensure the pivot selection is a real, per-call independent random draw, re-verified at implementation time |
:::warning[The single most dangerous mix-up is treating an expected-time bound as if it were a worst-case bound.] An engineer who reads "randomized quicksort is " and assumes this holds on every execution, not merely on average, will be unprepared for the rare but real run — a serious problem in latency-sensitive or adversarial settings (e.g., an attacker who can observe outputs and retry). Always state explicitly whether a bound is expected, worst-case, or high-probability (i.e., holds with probability ), since these are three different, non-interchangeable guarantees.
Pioneers & history
Randomized analysis, indicator random variables, and their combination for algorithm running times matured through the intersection of probability theory and computer science in the mid-to-late 20th century. Tony Hoare invented quicksort itself in 1959–1961; the randomized-pivot analysis and its rigorous expected-time treatment came later as randomized algorithms crystallized into their own subfield, driven by figures who formalized "algorithms that flip coins" as a first-class object of study alongside deterministic ones.
Origins · 1 minRichard M. Karp and how this was discovered
Karp's work — including randomized algorithms for pattern matching (Rabin–Karp), maximum matching, and probabilistic analysis of NP-hard heuristics — established the template used throughout this article: decompose a global cost into local indicator events, and let linearity of expectation do the heavy lifting. His 1985 Turing Award citation explicitly recognized contributions to the theory of algorithms including randomized and probabilistic techniques.
Where this matters
Expected running time analysis is not a theoretical nicety — it underlies working infrastructure. Standard library sort routines (introspective sort implementations in C++ and elsewhere) use randomized or pseudo-randomized pivot selection to defeat adversarial or pathological inputs while retaining the expected performance derived above. Hash table implementations in language runtimes and databases randomize their hash functions (universal hashing) specifically so that expected bucket-chain lengths stay regardless of what keys an adversary supplies — an application of the exact indicator-variable technique used here, just with "collision events" replacing "comparison events." Randomized min-cut (Karger's algorithm), randomized primality testing (Miller–Rabin, used in cryptographic key generation), skip lists (used in Redis and LevelDB as a simpler alternative to balanced trees), and randomized load balancing in distributed systems all rely on the same expectation-over-coin-flips paradigm. This analytic toolkit is also the direct stepping stone toward understanding Comparison-Based Sorting Lower Bounds, where the expected number of comparisons any correct sorting algorithm must perform is bounded below using an information-theoretic (entropy) argument dual to the indicator-variable upper-bound technique developed here — expectation appears on both sides of the sorting complexity story, as an achievable upper bound and as an unavoidable lower bound.
Ask the tutor: How would the indicator-variable argument change if we analyzed randomized quickselect instead of full quicksort?
Is "expected running time" the same as "average-case running time"?
Not exactly, though they use identical mathematics. Average-case running time (as discussed in analyses of deterministic algorithms) assumes a probability distribution over inputs — for instance, "assume all permutations of the input array are equally likely." That assumption may or may not hold for real workloads, and an adversary who knows the assumption can construct a bad input. Expected running time for a randomized algorithm instead treats the algorithm's own coin flips as the randomness, holding for every fixed input, because the adversary cannot predict random bits the algorithm generates at runtime. The formulas look the same (sums of indicator variables, linearity of expectation), but the guarantee's robustness differs substantially.
Why does linearity of expectation not require independence, and why is that such a big deal?
Linearity of expectation is a property of the expectation operator itself: follows directly from the definition of expectation as a weighted sum over the sample space, with no reference to whether and are independent. This matters enormously in practice because proving independence between events like "elements are compared" and "elements are compared" can be difficult or simply false — recursive algorithms create intricate dependencies between subproblems. Linearity lets analysts sidestep this entirely: compute each event's probability in isolation, then just add, regardless of how tangled the dependencies actually are.
Why is quicksort's worst case still even after randomization?
Randomization changes which inputs trigger bad behavior, not whether bad behavior is possible at all. With a random pivot, there always remains some sequence of coin flips — e.g., the pivot happens to be the minimum or maximum remaining element at every single recursive call — that produces the maximally unbalanced partition tree, giving comparisons. What randomization guarantees is that this sequence of coin flips has extremely small probability (roughly -scale rarity for the most pathological pattern, though weaker bad patterns are more likely but still exponentially rare), so it contributes negligibly to the expectation, even though it remains a logically possible outcome.
Can this indicator-variable technique be used for algorithms other than quicksort?
Yes — it is a general-purpose technique wherever total cost decomposes into a sum over pairwise or per-element events. Randomized selection (finding the -th smallest element) uses an almost identical pairwise-comparison argument to get expected time. Hash table analysis defines an indicator for "keys and collide under a random hash function" to bound expected chain length. Analyses of randomized incremental geometric algorithms (e.g., building a convex hull by inserting points in random order) use indicators for "point causes a structural change when inserted." Any time a global count can be phrased as "sum over elementary events of whether that event happens," this machinery applies.
Does a good expected running time bound guarantee low variance or a tight distribution around the mean?
No, and this is an important limitation to state honestly. An expectation bound like says nothing by itself about how tightly concentrates around that mean — it is consistent with a distribution that is usually fast but occasionally catastrophic (in principle, as long as the catastrophic outcomes are sufficiently rare to keep the average low). For randomized quicksort specifically, stronger results exist showing the running time is concentrated with high probability, typically proved via Chernoff-style tail bounds or recursive concentration arguments, but these are separate theorems layered on top of the expectation result, not automatic consequences of it.
Why relabel array elements by rank when analyzing randomized quicksort?
The relabeling is a bookkeeping convenience, not a restriction. Because quicksort's behavior depends only on the relative order of elements (which comparisons return true or false), not their actual numeric values, any input array of distinct elements can be relabeled through according to rank without changing a single comparison outcome the algorithm would make. This lets the analysis speak generically about "the sorted sequence " and immediately apply to any concrete array of distinct values, whether they are integers, strings, or complex records with a comparator.
How does this connect to lower bounds on sorting?
Expected-case analysis of a specific algorithm (like quicksort) gives an upper bound: some algorithm achieves expected comparisons. A separate, complementary question asks for a lower bound: must every comparison-based sorting algorithm perform at least comparisons, even in the best possible design? That question is answered using a decision-tree and information-theoretic argument, counted in expectation or worst case over all possible input orderings — a natural next topic once the expectation machinery here (indicator variables, linearity, harmonic-sum bounds) is comfortable, since the lower-bound proof reuses the same counting instincts in reverse.