Skip to the workspace
Pebellslearn by building
Analysis II: Recurrences, Amortisation & Randomness  ›  Lesson

Randomness as an Algorithm

Randomised Algorithms 30 minLet random choices replace a fixed rule, so no input is bad and only bad luck is — and measure how unlikely it is

dsa / Randomness as an Algorithm

Explore each scene at your own pace.

01 · One line changes

One line changes

Randomness as an Algorithm

Definition
A randomised algorithm makes some of its choices by chance, such as picking a quicksort pivot at random, so that no particular input is reliably bad and the expected running time is good on every input.
In plain words
If a rule is fixed, someone can find an input that always beats it. Rolling a die for the choice removes that weak spot: you can still be unlucky, but no input is guaranteed to hurt you, and real bad luck gets rarer as the job grows.

In short: a fixed pivot rule has some input that defeats it, and a chart that arrives already sorted is exactly that input for "always pick the last value". Picking the pivot at random removes the input from the equation: no input is bad any more, only bad luck is, and the chance of real bad luck shrinks to nothing as n grows. The same idea — remove the fixed rule an adversary (or an unlucky dataset) could aim at — also underlies a fair shuffle, reservoir sampling and Python's own hash randomisation.

The same sorted five-item chart quick-sorted two ways: a fixed last-element pivot peels off one item per level, n deep; a random pivot lands near the middle, about log n deep

Tunebox's weekly chart arrives already sorted by last week's position, and a lot of it barely moves. In section 3 you saw what that does to a quick sort that always takes the last value as its pivot: every pivot is the largest value left, every partition peels off one item, and the sort does n(n−1)/2n(n-1)/2 comparisons. On a chart of 64 tracks that is 2,016 comparisons where about 360 should do.

You could pick a cleverer fixed pivot, such as the middle, but any fixed rule has some input that defeats it, and somebody's data will be that input. This lesson takes the rule away from the input: let a random number pick the pivot. Then no input is bad. Only bad luck is, and you can measure exactly how unlikely it is.

One line changes

Here is your section 3 quick sort with its pivot choice pulled out into a function. It runs on a sorted chart of 10 tracks. The seeded generator makes the "random" choices the same on every run, so you can compare. Edit choose_pivot: try return hi, the old rule, and watch the comparison count jump.

your code, drawn · array

Your quick sort with a random pivot on a chart that is already sorted. The pivots land near the middle, so the ranges halve.

The only change from section 3 is two lines: pick an index at random, and swap that value into the pivot slot before partitioning. Everything else, including the correctness argument, is untouched. Whatever the random choices are, the output is sorted:

What does this print?
import random

rng = random.Random(2024)
chart = ["Aria", "Blue", "Cove", "Dawn", "Echo"]
shuffled = list(chart)
for i in range(len(shuffled) - 1, 0, -1):
    j = rng.randint(0, i)
    shuffled[i], shuffled[j] = shuffled[j], shuffled[i]
print(sorted(shuffled) == chart)
Scene 1 of 10
Project context and further resources
You're building a piece ofTunebox — the cost lab
This piece — quicksort_cost(): Counts what a random pivot really costs on a chart that arrives already sorted.
Scenario Tunebox's weekly chart arrives almost sorted, and the chart job has been timing out. The pivot lab shows the fixed pivot paying n² on exactly this input — and the random one paying n log n on every input.
quicksort_cost.py
Call the function you wrote — just like your app's frontend would. Edit the inputs and hit Call.
quicksort_cost(items, seed) → intHow many comparisons your random-pivot quick sort made.
try:
returned
Press Run to execute your code.
Press Check to run the tests for this lesson.
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.