A random cost
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 shuffle gives [2, 4, 1, 3]. best starts at 2, count 1. Then 4 beats 2: an update. 1 and 3 do not beat 4. This run costs 2 updates.
Run it again on the same input. This time the shuffle lands sorted: [1, 2, 3, 4]. Every number beats the one before, so best changes at every position: 4 updates, the most possible.
Once more: [4, 1, 3, 2]. The largest number comes first, nothing beats it, and the cost is 1. So the cost is a random variable: a number that depends on chance.
The average
A fair shuffle makes all 24 orders of 4 numbers equally likely. Run each once and drop a cube on the bar for its cost: 6, 11, 6, 1 runs cost 1, 2, 3 and 4 updates.
Expected cost is the average over all equally likely choices. The 24 runs make 50 updates in total, so E[cost] = 50/24 = 25/12 ≈ 2.08. The marker sits where the bars would balance.
Indicators and linearity
Listing orders gets slow. Instead give position i a lamp X_i that shows 1 if best changes there. Run [1, 3, 2, 4]: lamps 1, 2 and 4 light, and the cost is their sum, 1 + 1 + 0 + 1 = 3.
Position i updates only if it holds the largest of the first i numbers. In a fair shuffle that largest one is equally likely to be in any of those i places, so Pr[X_i = 1] = 1/i: lamps glow 1, ½, ⅓ and ¼.
Linearity of expectation: the average of a sum is the sum of the averages. So E[cost] = 1 + ½ + ⅓ + ¼ = 25/12, the same balance point as the 24 runs, with no list at all.
What it buys
The same sum works for any list size n: E[cost] = 1 + ½ + ... + 1/n, which grows like ln n. For n = 1000 that is about 7.49 updates, while the unlucky worst case is 1000. Expected O(log n).
The luck is in the shuffle, not the data. Even a sorted list, the worst input for a plain scan, gets shuffled first, so every input has the same expected cost, 25/12. Expected cost averages over the coin flips only.
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.