i=1i=2i=3i=41import random2def count_updates(a):3 random.shuffle(a)4 best, count = a[0], 15 for x in a[1:]:6 if x > best:7 best = x8 count += 19 return count01X1101X2½01X3⅓01X4¼1234E = 25/12 ≈ 2.08bestcount1234
Blocks: the numbers 1 to 4, height = value, hopping into each shuffled orderHistogram: one cube per shuffle, on the bar for its costLamps: indicator variables X_i, 1 when best changes at position icount_updates shuffles the list, then counts how often best changes; the blocks hop into each shuffled order and a cube flies to best on every update. The histogram holds one cube for each of the 24 equally likely orders; its balance point, 25/12, is the expected cost. The lamps X₁ to X₄ glow 1, ½, ⅓ and ¼ of the time, and by linearity of expectation they add up to the same 25/12.

A random cost

  1. A randomised algorithm makes random choices as it runs. This one shuffles the list, then scans it and counts how often best changes. That count is our cost. Same input, different shuffles, different costs.

The average

Indicators and linearity

What it buys

What happens

;; step 1/11 · random-cost
cost model: one unit each time best is set
  1  import random
  2  def count_updates(a):
  3      random.shuffle(a)
  4      best, count = a[0], 1
  5      for x in a[1:]:
  6          if x > best:
  7              best = x
  8              count += 1
  9      return count

input a = [3, 1, 4, 2], n = 4
random.shuffle(a) reorders a in place

Cost here counts the times best is set (line 4 once, then line 7 on each update). Comparisons are always n - 1 = 3, whatever the order, so they are not the interesting part. CLRS calls this the hiring problem: each update is a hire. Linearity of expectation, E[X + Y] = E[X] + E[Y], holds for any random variables, even dependent ones. MIT 6.006 uses the same indicator trick to show hash table chains have O(1) expected length.