Math Fundamentals18 sections · 814 units
Open in Course

Shuffle - Fisher-Yates Algorithm

The standard solution

The Fisher-Yates shuffle (also called Knuth shuffle) gives you a fair shuffle in O(n)O(n) time.

Here's the idea: for position ii from 00 to n1n-1, pick a random index jj where ij<ni \leq j < n, then swap elements at positions ii and jj. This ensures each element has equal probability of ending up in any position.

Why does this work? At step ii, you're choosing from the remaining (ni)(n-i) elements with equal probability. The product of these choices gives each permutation probability 1n!\frac{1}{n!}.