Random Permutations and Fisher-Yates
The randomized hiring algorithm began with "shuffle the candidates uniformly at random". Randomized quicksort, randomized search trees and many sampling methods begin the same way. The analysis of all of them assumes that the shuffle is uniform, so a shuffle that is only "pretty random" silently breaks every expected-cost bound built on it. This lesson proves that the Fisher-Yates shuffle is uniform, shows exactly how biased a popular shortcut is, and looks at a second method, sorting by random keys.
Card Shuffling introduces Fisher-Yates and riffle shuffles from the probability side. Here the focus is the proof, written as a loop invariant like the ones in Loop Invariants and the Correctness of Insertion Sort.
What "uniform" means
A permutation of distinct elements is one of their orderings. A procedure produces a uniform random permutation if every one of the orderings comes out with probability exactly .
That is a strong requirement. It is not enough that every element is equally likely to land in every position. The procedure "pick a random shift and rotate the array by " puts each element in each position with probability , yet it only ever produces of the orderings. Uniformity is about whole orderings.
The Fisher-Yates shuffle
The idea: choose the element for position 0 uniformly from all , then the element for position 1 uniformly from the that are left, and so on. Done in place, the elements not yet chosen are always the suffix of the array, so "choose one of them" is "swap a random suffix element to the front of the suffix".
FISHER-YATES(a) // a[0..n-1]; random(lo, hi) is uniform over lo..hi
1 for i = 0 to n - 2
2 j = random(i, n - 1)
3 swap a[i] and a[j] // a[i] is now finalIt uses random numbers and time. Python's random.shuffle is the same algorithm run from the right end to the left. In the trace below, each step freezes one more position of the prefix.
import random
def fisher_yates(a, rng):
a = list(a)
n = len(a)
for i in range(n - 1):
j = rng.randint(i, n - 1) # uniform over positions i .. n-1
a[i], a[j] = a[j], a[i]
print(f"i = {i}: swap with j = {j} -> {a} fixed prefix {a[:i + 1]}")
return a
rng = random.Random(7)
fisher_yates(["A", "B", "C", "D", "E"], rng)i = 0: swap with j = 2 -> ['C', 'B', 'A', 'D', 'E'] fixed prefix ['C']
i = 1: swap with j = 2 -> ['C', 'A', 'B', 'D', 'E'] fixed prefix ['C', 'A']
i = 2: swap with j = 3 -> ['C', 'A', 'D', 'B', 'E'] fixed prefix ['C', 'A', 'D']
i = 3: swap with j = 3 -> ['C', 'A', 'D', 'B', 'E'] fixed prefix ['C', 'A', 'D', 'B']
In C++
In C++, std::uniform_int_distribution draws . Its numbers are not Python's, so the swaps differ; seed 4 is used because its run also has a step with :
#include <cstdio>
#include <random>
#include <string>
#include <utility>
#include <vector>
using namespace std;
string show(const vector<char>& a, size_t len) { // the first len elements
string s = "[";
for (size_t k = 0; k < len; k++) s += string(k ? ", " : "") + "'" + a[k] + "'";
return s + "]";
}
vector<char> fisher_yates(vector<char> a, mt19937& rng) {
int n = (int)a.size();
for (int i = 0; i < n - 1; i++) {
int j = uniform_int_distribution<int>(i, n - 1)(rng); // uniform over i .. n-1
swap(a[i], a[j]);
printf("i = %d: swap with j = %d -> %s fixed prefix %s\n",
i, j, show(a, n).c_str(), show(a, i + 1).c_str());
}
return a;
}
int main() {
mt19937 rng(4);
fisher_yates({'A', 'B', 'C', 'D', 'E'}, rng);
}i = 0: swap with j = 4 -> ['E', 'B', 'C', 'D', 'A'] fixed prefix ['E']
i = 1: swap with j = 4 -> ['E', 'A', 'C', 'D', 'B'] fixed prefix ['E', 'A']
i = 2: swap with j = 3 -> ['E', 'A', 'D', 'C', 'B'] fixed prefix ['E', 'A', 'D']
i = 3: swap with j = 3 -> ['E', 'A', 'D', 'C', 'B'] fixed prefix ['E', 'A', 'D', 'C']
Note that is allowed (step 3 above): an element may stay where it is. Forbidding it gives Sattolo's algorithm, which only produces orderings that form a single cycle.
Proof that Fisher-Yates is uniform
Call an ordered sequence of distinct elements chosen from the a -permutation. There are of them.
Invariant. At the start of iteration , every possible -permutation appears as the prefix with probability exactly .
- Initialization. At the prefix is empty. There is one -permutation, the empty sequence, and it appears with probability .
- Maintenance. Fix an -permutation . It becomes the prefix after iteration exactly when two things happen: the prefix before the iteration is , which by the invariant has probability ; and the swap brings to position . Given the first event, is one of the elements in , and picks its position with probability . Multiplying, the probability is , which is the invariant for .
- Termination. The loop ends with , so every -permutation is the prefix with probability . The last element is whichever one is left, so the prefix determines the whole array: each of the orderings has probability .
For small there is an even more direct check. The random choices are , , and so on: equally likely runs in total. If every ordering is produced by exactly one run, the shuffle is uniform. The program below replays every run.
from collections import Counter
from itertools import product
def fisher_yates_with(choices, n):
# replay the shuffle with every choice given in advance: j_i = choices[i]
a = list(range(n))
for i, j in enumerate(choices):
a[i], a[j] = a[j], a[i]
return tuple(a)
for n in [3, 4]:
ranges = [range(i, n) for i in range(n - 1)] # j_i takes n - i values
counts = Counter(fisher_yates_with(c, n) for c in product(*ranges))
paths = sum(counts.values())
print(f"n = {n}: {paths} equally likely runs, {len(counts)} different permutations, "
f"each exactly once: {set(counts.values()) == {1}}")
if n == 3:
for p, k in sorted(counts.items()):
print(" ", p, k)n = 3: 6 equally likely runs, 6 different permutations, each exactly once: True
(0, 1, 2) 1
(0, 2, 1) 1
(1, 0, 2) 1
(1, 2, 0) 1
(2, 0, 1) 1
(2, 1, 0) 1
n = 4: 24 equally likely runs, 24 different permutations, each exactly once: True
In C++
The exhaustive replay in C++, written as a recursion that tries every choice of and undoes each swap afterwards. It prints the same result:
#include <cstdio>
#include <map>
#include <numeric>
#include <utility>
#include <vector>
using namespace std;
// replays Fisher-Yates on 0..n-1 for every possible choice vector j_0, j_1, ..., j_{n-2}
// with j_i in i..n-1, and counts how often each permutation comes out
void replay(int n, int i, vector<int>& a, map<vector<int>, int>& counts) {
if (i == n - 1) {
counts[a]++;
return;
}
for (int j = i; j < n; j++) {
swap(a[i], a[j]);
replay(n, i + 1, a, counts);
swap(a[i], a[j]); // undo, then try the next choice
}
}
int main() {
for (int n : {3, 4}) {
vector<int> a(n);
iota(a.begin(), a.end(), 0);
map<vector<int>, int> counts;
replay(n, 0, a, counts);
int paths = 0;
bool once = true;
for (const auto& [p, k] : counts) {
paths += k;
once = once && k == 1;
}
printf("n = %d: %d equally likely runs, %zu different permutations, "
"each exactly once: %s\n", n, paths, counts.size(), once ? "True" : "False");
if (n == 3)
for (const auto& [p, k] : counts)
printf(" (%d, %d, %d) %d\n", p[0], p[1], p[2], k);
}
}n = 3: 6 equally likely runs, 6 different permutations, each exactly once: True
(0, 1, 2) 1
(0, 2, 1) 1
(1, 0, 2) 1
(1, 2, 0) 1
(2, 0, 1) 1
(2, 1, 0) 1
n = 4: 24 equally likely runs, 24 different permutations, each exactly once: True
Fisher-Yates is a bijection between its random choices and the orderings. That is the cleanest possible kind of uniformity proof.
The tempting shortcut and its bias
A one-character change gives a famous bug: swap position with a position chosen from the whole array, , and let run over all positions.
NAIVE-SHUFFLE(a) // looks fine, is biased
1 for i = 0 to n - 1
2 j = random(0, n - 1)
3 swap a[i] and a[j]Now there are equally likely runs. Each ordering is produced by a whole number of runs, so for the shuffle to be uniform would have to divide . For it cannot: divides , but and share no common factor, so (which is at least 2) does not divide . Some orderings must be produced more often than others. Counting every run shows by how much.
from collections import Counter
from itertools import product
from math import factorial
def naive_with(choices, n):
a = list(range(n))
for i, j in enumerate(choices): # swap position i with ANY position j
a[i], a[j] = a[j], a[i]
return tuple(a)
for n in [3, 4]:
counts = Counter(naive_with(c, n) for c in product(range(n), repeat=n))
print(f"n = {n}: {n ** n} runs over {factorial(n)} permutations, {n ** n} / {factorial(n)} = {n ** n / factorial(n):.3f}")
print(" fewest runs:", min(counts.values()), " most runs:", max(counts.values()))
if n == 3:
for p, k in sorted(counts.items()):
print(" ", p, f"{k}/27")n = 3: 27 runs over 6 permutations, 27 / 6 = 4.500
fewest runs: 4 most runs: 5
(0, 1, 2) 4/27
(0, 2, 1) 5/27
(1, 0, 2) 5/27
(1, 2, 0) 5/27
(2, 0, 1) 4/27
(2, 1, 0) 4/27
n = 4: 256 runs over 24 permutations, 256 / 24 = 10.667
fewest runs: 8 most runs: 15
For four elements the most likely ordering comes out almost twice as often as the least likely one (15 runs against 8). A randomized algorithm fed by this shuffle has no valid analysis.
Permuting by sorting random keys
A second uniform method: give every element a random key and sort by the keys.
PERMUTE-BY-SORTING(a)
1 for i = 0 to n - 1
2 key[i] = random(0, n^3 - 1)
3 sort a using key as the sort keyIf all keys are distinct, the ordering of the keys is uniform by symmetry: every assignment of keys has the same probability as the one with any two keys swapped, so every relative order of the keys is equally likely, and sorting turns that order into the output. The method costs for a comparison sort, more than Fisher-Yates, but it is easy to run in parallel or inside a database (ORDER BY random()).
The weak spot is ties. A stable sort leaves tied elements in their input order, which biases the output towards the original order. Drawing keys from a range of size makes ties unlikely: each of the pairs ties with probability , so by a union bound
The program compares a key range of (ties everywhere) with for , exactly, over every possible key vector.
from collections import Counter
from fractions import Fraction
from itertools import product
def permute_by_sorting(a, keys):
order = sorted(range(len(a)), key=lambda i: keys[i]) # stable: ties keep input order
return tuple(a[i] for i in order)
a = ("A", "B", "C")
for key_range in [3, 27]:
counts = Counter(permute_by_sorting(a, keys) for keys in product(range(key_range), repeat=3))
total = key_range ** 3
distinct = sum(1 for keys in product(range(key_range), repeat=3) if len(set(keys)) == 3)
print(f"keys from 0..{key_range - 1}: Pr[all keys distinct] = {Fraction(distinct, total)}")
for p in sorted(counts):
print(" ", "".join(p), Fraction(counts[p], total))keys from 0..2: Pr[all keys distinct] = 2/9
ABC 10/27
ACB 4/27
BAC 4/27
BCA 4/27
CAB 4/27
CBA 1/27
keys from 0..26: Pr[all keys distinct] = 650/729
ABC 406/2187
ACB 364/2187
BAC 364/2187
BCA 364/2187
CAB 364/2187
CBA 325/2187
With keys from 3 values the input order ABC comes out ten times as often as its reverse. With 27 values the six orderings are close to each, but still not exact. To be exactly uniform, redraw the keys whenever two are equal (or break ties with fresh random bits); the expected number of redraws is tiny.
In practice: use the library shuffle (
random.shuffle,std::shuffle,Collections.shuffle), all of which are Fisher-Yates. The quality of the random number generator matters too: a generator with a 32-bit seed can reach at most orderings, far fewer than the orderings of a deck of cards.
Test yourself
In the Fisher-Yates loop for i = 0 to n - 2: j = random(i, n - 1); swap a[i], a[j], how many equally likely runs are there, and how many produce each ordering?
- runs, a varying number each
- runs, exactly one each
- runs, one each
- runs, each
Why can the naive shuffle (swap each position with a uniformly random position of the whole array) not be uniform for ?
- It uses too few random numbers
- Its equally likely runs cannot be split evenly among orderings, since 24 does not divide 256
- It never moves the first element
- It is uniform; the bias is a myth
What does the Fisher-Yates loop invariant state at the start of iteration ?
- The prefix is sorted
- Each element is in each position with probability
- Each possible -permutation is the prefix with probability
- The suffix is uniformly random
Permuting by sorting with random keys and a stable sort: what goes wrong when two keys are equal?
- The sort fails
- The tied elements keep their input order, biasing the output towards the original order
- Nothing, ties are harmless
- The output contains duplicates