Sub topic 5
The In-Place Fisher-Yates Shuffle
This chapter assumes you can read simple Python, index arrays from zero, and swap two elements. It also assumes you have read the earlier chapters on permutations, fair shuffles, the naive shuffle's bias, and the original 1938 method.
From Pencil and Paper to One Array
The original Fisher-Yates method crosses out numbers on a list and writes each chosen one onto a second list. Each pick has to scan for the k-th number not yet struck out, so a direct implementation takes O(n²) time. In 1964 Richard Durstenfeld published a version that avoids both the scan and the second list. It splits a single array into two regions:
- The unshuffled region is the prefix
items[0..i]. It holds the elements not yet placed. - The shuffled region is the suffix
items[i+1..n-1]. It holds the final positions, which are already decided.
At each step, the algorithm picks one element uniformly from the unshuffled region and swaps it into position i. The boundary then moves one place to the left. A swap replaces the crossing-out: the chosen element moves to the end of the region, and the element it displaces stays in the pool.
The Algorithm
import random
def fisher_yates(items):
for i in range(len(items) - 1, 0, -1):
j = random.randint(0, i) # inclusive on both ends: 0 <= j <= i
items[i], items[j] = items[j], items[i]
return items
print(fisher_yates(list(range(10))))Three details matter:
- The loop runs from
n - 1down to1. Whenireaches 0, only one element is left, and swapping it with itself would change nothing. jis drawn from0toiinclusive. The element at positionimust be allowed to stay where it is. Python'srandom.randintincludes both endpoints, unlikerandrange.- The function shuffles in place. It modifies the caller's list and returns that same list, not a copy.
A Worked Trace
Start with ['A', 'B', 'C', 'D']. Suppose the random draws come out as 1, 2, then 0.
| i | Range for j | j drawn | Array after swap | Shuffled suffix |
|---|---|---|---|---|
| 3 | 0..3 | 1 | A D C B | B |
| 2 | 0..2 | 2 | A D C B | C B |
| 1 | 0..1 | 0 | D A C B | A C B |
When i = 2, the draw picked j = i, so C stayed in place. That outcome is legal and necessary. Every element in the unshuffled region, including the one already at position i, needs the same chance of landing there.
The draws at each step have 4, 3, and 2 possible values, which gives 4 × 3 × 2 = 24 = 4! equally likely sequences. Each sequence produces a different ordering. A later chapter turns this count into a full proof. For now, compare it with the naive shuffle's 4⁴ = 256 sequences, which 24 does not divide.
Common Mistakes at This Stage
- Drawing
jfrom the whole array (0..n-1) brings back the naive shuffle's bias. - Using
random.randrange(i)instead ofrandint(0, i)excludesi. That bug gets its own chapter. - Expecting the function to leave its input unchanged. Pass
list(items)if you need to keep the original.
Exercise
Trace fisher_yates on [10, 20, 30] with random draws j = 0 (when i = 2) and then j = 1 (when i = 1). What is the final list, and how many distinct draw sequences are possible for a 3-element list?
Show answer
At i = 2, swapping positions 2 and 0 gives [30, 20, 10]. At i = 1 with j = 1, nothing moves, so the result is [30, 20, 10]. There are 3 × 2 = 6 possible draw sequences, which equals 3!, so each one maps to exactly one permutation.
Exercise
Why does the loop stop at i = 1 instead of running down to i = 0?
Show answer
At i = 0 the only possible choice is j = 0, so the swap would exchange the element with itself. That step makes no random choice and changes nothing, so the loop skips it.