TExcelTAD
Home › Foundations of Algorithm Analysis › Random Permutations and Fisher-Yates

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 nn distinct elements is one of their n!n! orderings. A procedure produces a uniform random permutation if every one of the n!n! orderings comes out with probability exactly 1n!\frac{1}{n!}.

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 ss and rotate the array by ss" puts each element in each position with probability 1n\frac{1}{n}, yet it only ever produces nn of the n!n! orderings. Uniformity is about whole orderings.

The Fisher-Yates shuffle

The idea: choose the element for position 0 uniformly from all nn, then the element for position 1 uniformly from the n−1n - 1 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".

text
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 final

It uses n−1n - 1 random numbers and Θ(n)\Theta(n) 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.

python · try it yourself
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 jj. Its numbers are not Python's, so the swaps differ; seed 4 is used because its run also has a step with j=ij = i:

cpp · try it yourself
#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 j=ij = i 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 kk distinct elements chosen from the nn a kk-permutation. There are n!(n−k)!\frac{n!}{(n-k)!} of them.

Invariant. At the start of iteration ii, every possible ii-permutation appears as the prefix a[0:i]a[0:i] with probability exactly (n−i)!n!\frac{(n-i)!}{n!}.

  • Initialization. At i=0i = 0 the prefix is empty. There is one 00-permutation, the empty sequence, and it appears with probability 1=n!n!1 = \frac{n!}{n!}.
  • Maintenance. Fix an (i+1)(i+1)-permutation x0,…,xix_0, \ldots, x_i. It becomes the prefix after iteration ii exactly when two things happen: the prefix before the iteration is x0,…,xi−1x_0, \ldots, x_{i-1}, which by the invariant has probability (n−i)!n!\frac{(n-i)!}{n!}; and the swap brings xix_i to position ii. Given the first event, xix_i is one of the n−in - i elements in a[i:n]a[i:n], and jj picks its position with probability 1n−i\frac{1}{n-i}. Multiplying, the probability is (n−i)!n!⋅1n−i=(n−i−1)!n!\frac{(n-i)!}{n!} \cdot \frac{1}{n-i} = \frac{(n-i-1)!}{n!}, which is the invariant for i+1i + 1.
  • Termination. The loop ends with i=n−1i = n - 1, so every (n−1)(n-1)-permutation is the prefix a[0:n−1]a[0:n-1] with probability 1!n!=1n!\frac{1!}{n!} = \frac{1}{n!}. The last element is whichever one is left, so the prefix determines the whole array: each of the n!n! orderings has probability 1n!\frac{1}{n!}.

For small nn there is an even more direct check. The random choices are j0∈{0,…,n−1}j_0 \in \{0, \ldots, n-1\}, j1∈{1,…,n−1}j_1 \in \{1, \ldots, n-1\}, and so on: n⋅(n−1)⋯2=n!n \cdot (n-1) \cdots 2 = n! equally likely runs in total. If every ordering is produced by exactly one run, the shuffle is uniform. The program below replays every run.

python · try it yourself
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 jij_i and undoes each swap afterwards. It prints the same result:

cpp · try it yourself
#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 ii with a position chosen from the whole array, j∈{0,…,n−1}j \in \{0, \ldots, n-1\}, and let ii run over all nn positions.

text
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 nnn^n equally likely runs. Each ordering is produced by a whole number of runs, so for the shuffle to be uniform n!n! would have to divide nnn^n. For n≥3n \ge 3 it cannot: n−1n - 1 divides n!n!, but n−1n - 1 and nn share no common factor, so n−1n - 1 (which is at least 2) does not divide nnn^n. Some orderings must be produced more often than others. Counting every run shows by how much.

python · try it yourself
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.

text
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 key

If 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 nn keys is equally likely, and sorting turns that order into the output. The method costs Θ(nlog⁡n)\Theta(n \log n) 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 n3n^3 makes ties unlikely: each of the (n2)\binom{n}{2} pairs ties with probability 1n3\frac{1}{n^3}, so by a union bound

Pr⁡[some tie]≤(n2)⋅1n3<12n\Pr[\text{some tie}] \le \binom{n}{2} \cdot \frac{1}{n^3} < \frac{1}{2n}

The program compares a key range of 33 (ties everywhere) with 27=3327 = 3^3 for n=3n = 3, exactly, over every possible key vector.

python · try it yourself
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 16=364.52187\frac{1}{6} = \frac{364.5}{2187} 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 2322^{32} orderings, far fewer than the 52!52! 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?

  1. nnn^n runs, a varying number each
  2. n!n! runs, exactly one each
  3. 2n2^n runs, one each
  4. n2n^2 runs, nn each

Why can the naive shuffle (swap each position with a uniformly random position of the whole array) not be uniform for n=4n = 4?

  1. It uses too few random numbers
  2. Its 44=2564^4 = 256 equally likely runs cannot be split evenly among 4!=244! = 24 orderings, since 24 does not divide 256
  3. It never moves the first element
  4. It is uniform; the bias is a myth

What does the Fisher-Yates loop invariant state at the start of iteration ii?

  1. The prefix a[0:i]a[0:i] is sorted
  2. Each element is in each position with probability 1n\frac{1}{n}
  3. Each possible ii-permutation is the prefix a[0:i]a[0:i] with probability (n−i)!n!\frac{(n-i)!}{n!}
  4. The suffix a[i:n]a[i:n] is uniformly random

Permuting by sorting with random keys and a stable sort: what goes wrong when two keys are equal?

  1. The sort fails
  2. The tied elements keep their input order, biasing the output towards the original order
  3. Nothing, ties are harmless
  4. The output contains duplicates