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 O(nlog⁡n)O(n \log n) 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.

Key takeaways
  • 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: Xij=1X_{ij} = 1 if event ijij occurs, else 00, so E[Xij]=Pr⁡[ij occurs]E[X_{ij}] = \Pr[ij \text{ occurs}].
  • Linearity of expectation, E[∑Xi]=∑E[Xi]E[\sum X_i] = \sum E[X_i], holds unconditionally — no independence between the XiX_i required.
  • Randomized quicksort achieves O(nlog⁡n)O(n \log n) expected comparisons on every input, by summing pairwise-comparison probabilities 2j−i+1\frac{2}{j-i+1} 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.
The core insight

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 T(n)T(n) 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 nn. 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 TT whose randomness comes entirely from those internal coin flips. The expected running time is E[T]E[T], the average of TT 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 n!n! 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 O(nlog⁡n)O(n\log n) 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 E[T]E[T] is the indicator random variable. For an event AA in a sample space, define

XA={1if A occurs0otherwise.X_A = \begin{cases} 1 & \text{if } A \text{ occurs} \\ 0 & \text{otherwise.} \end{cases}

A one-line but load-bearing fact: E[XA]=Pr⁡[A]E[X_A] = \Pr[A], since E[XA]=1⋅Pr⁡[A]+0⋅Pr⁡[Aˉ]=Pr⁡[A]E[X_A] = 1\cdot \Pr[A] + 0 \cdot \Pr[\bar A] = \Pr[A]. 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,

E[∑iXi]=∑iE[Xi],E\Big[\sum_{i} X_i\Big] = \sum_i E[X_i],

lets us compute the expectation of the sum by adding up the individual, easy-to-compute probabilities Pr⁡[eventi]\Pr[\text{event}_i] — crucially, even when the XiX_i 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 A1,…,AmA_1, \dots, A_m (often "pair (i,j)(i,j) triggers the operation") and define Xk=1[Ak]X_k = \mathbb{1}[A_k] so that the total count X=∑kXkX = \sum_k X_k. 3. Compute Pr⁡[Ak]\Pr[A_k] 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: E[X]=∑kPr⁡[Ak]E[X] = \sum_k \Pr[A_k], then bound this sum (often by comparison to a harmonic series or a geometric series) to get a closed form such as O(nlog⁡n)O(n \log n). 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 Θ(n2)\Theta(n^2) worst case (triggered by already-sorted input under a fixed pivot rule) into an O(nlog⁡n)O(n\log n) 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 z1<z2<⋯<znz_1 < z_2 < \dots < z_n (any fixed array's elements can be relabeled by rank without changing the comparison structure). Define, for i<ji < j:

Xij=1[zi and zj are compared at some point during the algorithm].X_{ij} = \mathbb{1}[z_i \text{ and } z_j \text{ are compared at some point during the algorithm}].

The total number of comparisons performed by the algorithm is exactly

X=∑i=1n−1∑j=i+1nXij,X = \sum_{i=1}^{n-1}\sum_{j=i+1}^{n} X_{ij},

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 zi,zjz_i, z_j with i<ji < j, and the set Zij={zi,zi+1,…,zj}Z_{ij} = \{z_i, z_{i+1}, \dots, z_j\} of all elements between them (inclusive), of size j−i+1j - i + 1. Two facts:

  • ziz_i and zjz_j are compared if and only if one of them is chosen as a pivot before any other element of ZijZ_{ij} is chosen as a pivot. (If some element strictly between them is pivoted first, ziz_i and zjz_j 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 ZijZ_{ij} are first chosen as pivots (among calls that contain all of ZijZ_{ij}) is a uniformly random permutation of ZijZ_{ij}.

Hence

Pr⁡[Xij=1]=Pr⁡[zi or zj is the first of Zij to be pivoted]=2j−i+1.\Pr[X_{ij} = 1] = \Pr[z_i \text{ or } z_j \text{ is the first of } Z_{ij} \text{ to be pivoted}] = \frac{2}{j - i + 1}.

By linearity of expectation (no independence between the XijX_{ij} needed):

E[X]=∑i=1n−1∑j=i+1n2j−i+1.E[X] = \sum_{i=1}^{n-1}\sum_{j=i+1}^{n} \frac{2}{j-i+1}.

Substitute k=j−ik = j - i (so kk ranges from 11 to n−1n-1, and for each kk there are n−kn-k valid pairs (i,j)(i,j)):

E[X]=∑i=1n−1∑k=1n−i2k+1<∑i=1n−1∑k=1n2k=2∑i=1n−1Hn=O(nHn)=O(nlog⁡n),E[X] = \sum_{i=1}^{n-1}\sum_{k=1}^{n-i} \frac{2}{k+1} < \sum_{i=1}^{n-1}\sum_{k=1}^{n} \frac{2}{k} = 2\sum_{i=1}^{n-1} H_n = O(n H_n) = O(n \log n),

using the harmonic number bound Hn=O(log⁡n)H_n = O(\log n). This gives the clean, famous result:

E[comparisons in randomized quicksort]=O(nlog⁡n)for every input.E[\text{comparisons in randomized quicksort}] = O(n \log n) \quad \text{for every input}.
Figure
Indicator events for randomized quicksort: ziz_i and zjz_j are compared only if one of them is pivoted before any element strictly between them
Sorted ranks z1..z9, comparing z2 and z7 z1 z2 z3 z4 z5 z6 z7 z8 z9 Z_ij = {z2,...,z7}, size 6 Compared IFF z2 or z7 is the first of these 6 elements pivoted Pr[compared] = 2 / 6 = 1/3 If z4 (orange, strictly between) is pivoted first, z2 and z7 fall into different subarrays and are never compared.

Complexity & correctness

Time complexity. The derivation above shows E[comparisons]=O(nlog⁡n)E[\text{comparisons}] = O(n\log n) 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 O(n)O(n) per level of recursion, so the total expected running time is O(nlog⁡n)O(n\log n) as well. This should be contrasted with:

  • Worst case (over both input and coin flips): still Θ(n2)\Theta(n^2), 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: Θ(nlog⁡n)\Theta(n \log n), when pivots repeatedly split the array evenly.
  • Expected case (this article's subject): Θ(nlog⁡n)\Theta(n\log n) for every fixed input, because the O(n2)O(n^2) worst case has probability that decays exponentially in nn and contributes negligibly to the expectation.

Space complexity. Expected recursion depth is O(log⁡n)O(\log n) (by a similar indicator/probabilistic argument on the size of subproblems shrinking geometrically in expectation), giving expected O(log⁡n)O(\log n) auxiliary stack space; a bad sequence of pivots can still cause O(n)O(n) depth, so implementations often recurse on the smaller partition first and iterate on the larger one to guarantee O(log⁡n)O(\log n) 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 zi,zjz_i, z_j are compared at most once, across the whole execution. This is what licenses writing total comparisons as ∑i<jXij\sum_{i<j} X_{ij} with no double-counting. 2. The "first pivoted wins" characterization is exact, not approximate. If neither ziz_i nor zjz_j is the first pivot chosen among ZijZ_{ij}, some element strictly between them is pivoted first and permanently separates ziz_i from zjz_j into different recursive calls — they can never be compared afterward. Conversely if ziz_i (or zjz_j) is the first of ZijZ_{ij} pivoted, it is compared directly against every other currently co-resident element of ZijZ_{ij}, including zjz_j, during that partition step. This gives the iff characterization used above, and hence the exact probability 2/(j−i+1)2/(j-i+1) (a uniformly random permutation places any one of j−i+1j-i+1 elements first with equal probability 1/(j−i+1)1/(j-i+1), and we want either of two designated elements to be first). 3. Linearity needs no independence. The events XijX_{ij} are certainly not independent (e.g., knowing z1,z2z_1, z_2 were compared changes the conditional structure of later comparisons), but E[∑Xij]=∑E[Xij]E[\sum X_{ij}] = \sum E[X_{ij}] 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 Θ(n2)\Theta(n^2) pathological case. For applications demanding hard real-time guarantees, expectation bounds must be paired with concentration results (e.g., Chernoff-style tail bounds showing Pr⁡[T>c⋅nlog⁡n]\Pr[T > c\cdot n\log n] decays exponentially in cc) 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 n=5n = 5:

A=[1,2,3,4,5].A = [1, 2, 3, 4, 5].

Ranks equal values here, so zi=iz_i = i. We compute Pr⁡[Xij=1]=2j−i+1\Pr[X_{ij}=1] = \frac{2}{j-i+1} for all (52)=10\binom{5}{2}=10 pairs and sum.

pair (i,j)(i,j)j−i+1j-i+1Pr⁡[Xij=1]=2j−i+1\Pr[X_{ij}=1] = \frac{2}{j-i+1}
(1,2)21.000
(1,3)30.667
(1,4)40.500
(1,5)50.400
(2,3)21.000
(2,4)30.667
(2,5)40.500
(3,4)21.000
(3,5)30.667
(4,5)21.000

Summing the right column: 1.0+0.667+0.5+0.4+1.0+0.667+0.5+1.0+0.667+1.0=8.41.0+0.667+0.5+0.4+1.0+0.667+0.5+1.0+0.667+1.0 = 8.4 (approximately), so

E[comparisons]≈8.4E[\text{comparisons}] \approx 8.4

for this n=5n=5 sorted array — versus the worst-case (52)=10\binom{5}{2}=10 comparisons a fixed always-pick-first-element quicksort would need on this same input (achieving its full Θ(n2)\Theta(n^2) regime), and versus the theoretical best case around nlog⁡2n≈11.6n\log_2 n \approx 11.6 comparisons for merge-sort-style optimal splitting scaled to this small n (small-nn 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 33 (value 33), splitting into [1,2][1,2] and [4,5][4,5]; then [1,2][1,2] picks pivot 11 (value 11, so no further split needed on that side after one comparison), and [4,5][4,5] picks pivot 22 (value 44 relative to that subarray). Tallying comparisons in this run: partitioning around 33 costs 44 comparisons (comparing 1,2,4,51,2,4,5 against pivot 33); partitioning [1,2][1,2] around 11 costs 11 comparison; partitioning [4,5][4,5] around 44 costs 11 comparison. Total for this particular run: 66 comparisons — below the expectation of 8.48.4, 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

PitfallWhy it's wrongFix
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 practiceState clearly which randomness (input vs. algorithm coins) the expectation is over
Assuming indicator variables must be independent before applying linearityLinearity of expectation holds for any random variables, dependent or notNever invoke independence unless you need E[XY]=E[X]E[Y]E[XY]=E[X]E[Y] or variance bounds — for expectation of a sum, skip the issue entirely
Treating "expected O(nlog⁡n)O(n\log n)" as a guarantee that no run is ever slowExpectation is an average; a Θ(n2)\Theta(n^2) run is possible (e.g., always picking the min pivot), just very improbablePair expectation bounds with tail/concentration arguments when worst-run guarantees matter
Double-counting comparisons when defining eventsIf the algorithm could compare a pair multiple times, summing indicators over pairs undercounts or overcounts total workVerify (as done above) that each pair is compared at most once before writing total cost as ∑Xij\sum X_{ij}
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 caseEnsure 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 O(nlog⁡n)O(n\log n)" and assumes this holds on every execution, not merely on average, will be unprepared for the rare but real Θ(n2)\Theta(n^2) 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 1−n−c1 - n^{-c}), 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
RM
Richard M. Karp
1935–present · Pioneer of randomized and probabilistic algorithm analysis, RSA-award and Turing-award winning computer scientist

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.

History
1962
C.A.R. Hoare publishes quicksort, later analyzed in both deterministic worst/average forms.
1976
Michael Rabin formalizes randomized algorithms as a rigorous computational model (Miller–Rabin primality testing).
1980
s: Richard Karp and collaborators develop systematic probabilistic analysis techniques for randomized algorithms.
1990
Motwani and Raghavan-era textbooks popularize indicator-variable analysis for randomized quicksort and hashing.
2000
s: Randomized algorithms and their expected-time analyses become standard curriculum alongside deterministic worst-case analysis.

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 O(nlog⁡n)O(n\log n) 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 O(1)O(1) 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: E[X+Y]=E[X]+E[Y]E[X+Y] = E[X]+E[Y] follows directly from the definition of expectation as a weighted sum over the sample space, with no reference to whether XX and YY are independent. This matters enormously in practice because proving independence between events like "elements zi,zjz_i,z_j are compared" and "elements zk,zlz_k,z_l 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 Θ(n2)\Theta(n^2) 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 Θ(n2)\Theta(n^2) comparisons. What randomization guarantees is that this sequence of coin flips has extremely small probability (roughly 1n!\frac{1}{n!}-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 kk-th smallest element) uses an almost identical pairwise-comparison argument to get expected O(n)O(n) time. Hash table analysis defines an indicator for "keys xx and yy 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 pp 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 E[T]=O(nlog⁡n)E[T] = O(n\log n) says nothing by itself about how tightly TT 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 nn distinct elements can be relabeled 11 through nn according to rank without changing a single comparison outcome the algorithm would make. This lets the analysis speak generically about "the sorted sequence z1<⋯<znz_1 < \cdots < z_n" and immediately apply to any concrete array of nn 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 O(nlog⁡n)O(n\log n) expected comparisons. A separate, complementary question asks for a lower bound: must every comparison-based sorting algorithm perform at least Ω(nlog⁡n)\Omega(n\log n) 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 n!n! 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.

Before this

Where this leads