47.05.02 · theoretical-cs / randomized-algorithms

Randomized Algorithms: Quicksort, Skip Lists, and Treaps

shipped3 tiersLean: none

Anchor (Master): Cormen, Leiserson, Rivest & Stein 2022 Introduction to Algorithms 4e (MIT Press) §5.3, §7.3-7.4, §12.4; Motwani & Raghavan 1995 Randomized Algorithms (Cambridge) Ch. 1-2 (Las Vegas vs Monte Carlo, expected running time analysis, skip lists and treaps)

Intuition Beginner

Imagine you are sorting a deck of cards. One strategy: pick a card at random, split the deck into cards smaller and cards larger, then sort each half. This is randomized quicksort. The random choice means you never get stuck with a bad split — on average, the splits are good enough to sort quickly.

Randomized algorithms use coin flips (or more generally, random number generation) to make decisions during execution. There are two flavours. Las Vegas algorithms always produce the correct answer, but their running time varies. Monte Carlo algorithms run in a fixed time but might produce a wrong answer with small probability.

Randomized quicksort is Las Vegas: it always correctly sorts the array, and its expected running time is regardless of the input. The randomness is in the algorithm, not the input. No adversary can craft a worst-case input because the pivot choice is random.

Skip lists extend this idea to dictionaries. Instead of maintaining a complex balance invariant (like red-black trees), you build multiple levels of linked lists where each node is promoted to a higher level with probability 1/2. Search starts at the top level and drops down, achieving expected time with a simple implementation.

Treaps combine binary search trees with random priorities. Each key gets a random priority, and the tree is a heap on priorities. The randomness of priorities ensures the tree is balanced in expectation, giving expected time for all operations.

Visual Beginner

Skip list for keys {3, 7, 12, 21, 35, 42}:

Level 3:  HEAD ─────────────────────────→ 42
Level 2:  HEAD ──────→ 12 ──────────────→ 42
Level 1:  HEAD ──→ 7 ──→ 12 ──→ 21 ────→ 42
Level 0:  HEAD → 3 → 7 → 12 → 21 → 35 → 42

Each node was promoted to higher levels with probability 1/2. To search for 21: start at level 3, move right (42 is too large), drop to level 2, move right (12), move right (42 too large), drop to level 1, move right (21 found).

Structure Expected search time Worst case Code complexity
Sorted array Simple but insert is
Red-black tree Complex
Skip list unlikely Simple
Treap unlikely Moderate

Worked example Beginner

We sort the array [4, 1, 7, 3, 6] using randomized quicksort.

Step 1. Choose a random pivot from [4, 1, 7, 3, 6]. Suppose we pick 4 (index 0).

Partition: elements less than 4 go left, elements greater go right.

Left: [1, 3]. Right: [7, 6]. Pivot: [4].

Step 2a. Sort left [1, 3]. Choose random pivot: suppose 1.

Partition: left [], right [3]. Pivot [1].

Result: [1, 3].

Step 2b. Sort right [7, 6]. Choose random pivot: suppose 6.

Partition: left [], right [7]. Pivot [6].

Result: [6, 7].

Combine. [1, 3] + [4] + [6, 7] = [1, 3, 4, 6, 7].

The pivot choices led to a balanced partition (2 elements on each side of 4). In the worst case, if we always picked the smallest element, each partition would give 0 and elements, leading to time. But the probability of consistently bad choices is exponentially small.

Check your understanding Beginner

Formal definition Intermediate+

Definition (Las Vegas algorithm). A Las Vegas algorithm is a randomized algorithm that always produces a correct output but whose running time is a random variable. The expected running time is .

Definition (Monte Carlo algorithm). A Monte Carlo algorithm is a randomized algorithm that runs in deterministic time but may produce an incorrect output with probability at most (the error probability).

Definition (randomized quicksort). Randomized quicksort selects a pivot uniformly at random from the subarray and partitions around it:

RANDOMIZED-QUICKSORT(A, p, r):
  if p < r:
    q = RANDOMIZED-PARTITION(A, p, r)
    RANDOMIZED-QUICKSORT(A, p, q - 1)
    RANDOMIZED-QUICKSORT(A, q + 1, r)

Theorem (expected running time of randomized quicksort). The expected running time of randomized quicksort on an array of elements is .

Proof sketch. Let be the elements in sorted order. Define indicator if and are compared during the algorithm. The total number of comparisons is . By linearity of expectation, .

Two elements and are compared if and only if one of them is chosen as a pivot before any element between them (i.e., ) is chosen. Among the set , each element is equally likely to be chosen as pivot first. So .

Therefore .

Definition (skip list). A skip list for a sorted set of elements is a collection of linked lists where contains all elements of in sorted order, and each element is promoted from to independently with probability . The maximum level is with high probability.

Theorem (skip list search cost). The expected cost of a search in a skip list with elements is .

Definition (treap). A treap for a set of key-priority pairs is a binary search tree on the keys that is simultaneously a max-heap on the priorities. When priorities are chosen independently and uniformly at random, the expected height of the treap is .

Counterexamples to common slips

  • "Randomized quicksort has worst case so it is bad." The worst case is exponentially unlikely. For any fixed input, the probability of time is at most for any constant . In practice, randomized quicksort is faster than mergesort due to better cache behaviour.

  • "Skip lists are probabilistically balanced but unreliable." The failure probability is exponentially small. The probability that a skip list search takes more than steps is at most for appropriate constants.

  • "Treaps can degenerate into linked lists." In expectation, the height is . The probability of height exceeding is exponentially small. Treaps are "balanced with high probability."

Key theorem with proof Intermediate+

Theorem (treap expected height). The expected height of a treap on keys with random priorities is .

Proof. Let be the indicator that node is an ancestor of node (or vice versa). The depth of node is and the height is .

Node is an ancestor of node iff among the nodes on the path from to in the key ordering, node has the highest priority. Since priorities are random, this probability is for each pair.

By linearity of expectation, where is the -th harmonic number.

For the height, . While the maximum of expectations can exceed the expectation of the maximum, a more careful analysis using the fact that is the sum of independent indicators (they are not independent, but weakly correlated) gives . More precisely, by a result of Devroye (1986), for large .

Bridge. Randomized data structures are the foundational reason simple algorithms can match the performance guarantees of deterministic structures: randomisation replaces complex invariant maintenance with probabilistic balance. This builds toward the hashing algorithms of 47.05.01, where universal hashing achieves expected performance with simpler code than deterministic alternatives, and it appears again in 47.05.03 where primality testing uses randomness to achieve polynomial time with high probability. The central insight is that random choices are "good on average" — this is exactly the principle that makes randomized quicksort, skip lists, and treaps work. Putting these together yields a design philosophy: when a deterministic invariant is expensive to maintain, replace it with a random choice that achieves the same effect in expectation.

Exercises Intermediate+

Lean formalization Intermediate+

Mathlib has Probability.ProbabilityMassFunction, Data.Tree, and Sort.QuickSort (a deterministic quicksort), but no formalisation of randomized quicksort, skip lists, or treaps. The foundational gap is the absence of a probabilistic computation framework that tracks expected running time, the indicator-variable analysis of quicksort comparisons, and the geometric-random-variable analysis of skip list levels. A RandT (randomised computation) monad with an expected-cost measure would be the load-bearing first step. This unit ships without a lean_module.

Advanced results Master

Three results sharpen the theory of randomized algorithms for sorting and searching.

Theorem 1 (high-probability bound for quicksort). With probability at least (for any constant ), randomized quicksort runs in time.

This follows from a Chernoff-bound analysis of the number of comparisons. The tail decays exponentially, so even moderate deviations from the expected comparisons are unlikely. This means randomized quicksort is not just good on average — it is good with overwhelming probability.

Theorem 2 (skip list with high probability). All operations (search, insert, delete) in a skip list with elements run in time with probability at least for any constant .

The proof uses the fact that the skip list height is with high probability (union bound on geometric random variables) and that the expected number of horizontal moves per level is with exponentially small tail. This matches the guarantees of balanced search trees without the complex rebalancing logic [Motwani & Raghavan Ch. 2].

Theorem 3 (treap split and merge). Treaps support split and merge operations in expected time.

Split(, ) divides treap into two treaps at key . Merge(, ) combines two treaps (all keys in are less than all keys in ). Both operations are fundamental building blocks for more advanced data structures like interval trees and link-cut trees.

Synthesis. Randomized data structures are the foundational reason simple algorithms can achieve logarithmic-time performance: randomisation replaces deterministic invariants with probabilistic ones that hold with high probability. The central insight is that random choices are "good on average" — this is exactly the principle that unifies randomized quicksort, skip lists, and treaps, despite their very different structures. This builds toward the broader theory of randomized algorithms, where randomness serves as a resource that can simplify algorithm design, improve performance, and enable computations that are difficult or impossible deterministically. Putting these together with the universal hashing of 47.05.01 and the primality testing of 47.05.03 yields a unified framework for using randomness as an algorithmic tool.

Full proof set Master

Proposition 1 (randomized quicksort expected comparisons). The expected number of comparisons in randomized quicksort on distinct elements is at most .

Proof. Let be the elements in sorted order. Define . Total comparisons: .

Claim: .

The elements form a contiguous range in sorted order. When quicksort first selects a pivot from this range, and are compared iff the pivot is or (then one is compared to all others in the range). If any with is the pivot, then and are placed in different subarrays and never compared. Since the pivot is chosen uniformly at random, the first pivot from this range is equally likely to be any of the elements. So .

Proposition 2 (skip list height bound). The height of a skip list with elements exceeds with probability at most .

Proof. Each element is promoted to level with probability . The height where . By union bound:

Proposition 3 (treap expected depth). The expected depth of any node in a treap with keys and random priorities is at most .

Proof. The depth of node is . Node is an ancestor of node iff has the highest priority among . Since priorities are uniform and independent, this probability is . So:

Connections Master

  • 47.05.01 — Universal and perfect hashing use randomisation to achieve expected dictionary operations; skip lists and treaps achieve for comparison-based structures.

  • 47.04.02 — Red-black trees provide deterministic worst-case guarantees; treaps provide the same expected bound with simpler code.

  • 47.04.01 — Amortized analysis bounds the total cost over sequences; randomized analysis bounds the expected cost per operation.

  • 50.03.01 — Big-O and expected-value analysis are the analytical tools used throughout.

Historical & philosophical context Master

Randomized quicksort was analysed by Hoare (1962) in his original paper on quicksort, where he noted that random pivot selection avoids worst-case behaviour. The formal analysis using indicator random variables is due to the textbook treatment by CLRS [CLRS §7.4].

Skip lists were invented by William Pugh in 1990. His motivation was to create a probabilistic alternative to balanced trees that is simpler to implement and has comparable performance. The key insight was that multiple levels of linked lists with geometrically decreasing density mimic the structure of a balanced tree without requiring explicit balancing [Motwani & Raghavan Ch. 2].

Treaps were introduced by Aragon and Seidel in 1989 (published 1996). The name "treap" was coined by Cecilia Aragon, who was also a championship-level rock climber. The treap's simplicity — a BST with random priorities — demonstrates a philosophical point: randomness can replace algorithmic cleverness. Instead of a complex rebalancing algorithm, the treap relies on the fact that random priorities produce balanced trees in expectation.

The broader philosophical point is that randomness is a computational resource. Just as time and space constrain what algorithms can do, randomness expands what can be done efficiently. The question of whether randomness genuinely helps (the BPP vs P question of 47.03.01) remains one of the central open problems in complexity theory.

Bibliography Master

@book{clrs2022,
  author    = {Cormen, Thomas H. and Leiserson, Ronald L. and Rivest, Clifford and Stein, Christopher},
  title     = {Introduction to Algorithms},
  edition   = {4th},
  publisher = {MIT Press},
  year      = {2022},
}
@book{motwani1995,
  author    = {Motwani, Rajeev and Raghavan, Prabhakar},
  title     = {Randomized Algorithms},
  publisher = {Cambridge University Press},
  year      = {1995},
}
@article{pugh1990skip,
  author  = {Pugh, William},
  title   = {Skip Lists: A Probabilistic Alternative to Balanced Trees},
  journal = {Communications of the ACM},
  volume  = {33},
  number  = {6},
  pages   = {668--676},
  year    = {1990},
}
@article{aragon1989randomized,
  author  = {Aragon, Cecilia R. and Seidel, Raimund},
  title   = {Randomized Search Trees},
  journal = {Algorithmica},
  volume  = {16},
  pages   = {464--497},
  year    = {1996},
  note    = {Preliminary version 1989},
}