Fisher-Yates Shuffle: The Correct Way to Shuffle an Array
The Fisher-Yates shuffle in JavaScript and Python, why sort(() => Math.random() - 0.5) is biased, with 6 million measured runs and exact counts for modulo bias.
On this page ⌄
The correct way to shuffle is the Fisher-Yates shuffle: walk the array from the last index down to 1, and swap each element with the element at a random index from 0 up to and including the current index. Do not shuffle with arr.sort(() => Math.random() - 0.5): in Node 25.8 it put [1,2,3] into the original order or into 213 about 25% of the time each, instead of the 16.7% a fair shuffle gives. To shuffle a list without writing code, use the list randomizer.
The algorithm in JavaScript
function shuffle(arr) {
for (let i = arr.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1)); // 0 <= j <= i
[arr[i], arr[j]] = [arr[j], arr[i]];
}
return arr;
}
It shuffles in place in O(n) time. The original method was published by Ronald Fisher and Frank Yates in 1938 as a pencil-and-paper procedure; the in-place computer version above was introduced by Richard Durstenfeld in 1964 and popularised by Knuth as Algorithm P (Wikipedia, Fisher-Yates shuffle).
Why it is fair: at step i there are i + 1 positions to choose from, so the full run has n x (n-1) x ... x 2 x 1 = n! equally likely index sequences, and each one produces a different permutation. For n = 4 that is 24 sequences. Enumerating every one of them in code gives all 24 permutations exactly once (Node 25.8 and, independently, Python 3.11 itertools.product).
Why sort with Math.random() is biased
sort(() => Math.random() - 0.5) hands the sort algorithm a comparator that contradicts itself: comparing the same two items twice can give opposite answers. A sorting algorithm assumes a consistent order, so the result depends on how that particular algorithm happens to compare items, and nothing makes all permutations equally likely. V8 has used Timsort for Array.prototype.sort since V8 7.0 (Chrome 70), according to the V8 blog post Getting things sorted in V8. The measurements below are for that engine only; other engines use other algorithms and may show different skew.
Measured: 6,000,000 shuffles of [1,2,3]
Run with Node v25.8.0 (V8 14.1.146.11). The chi-square statistic and p-value come from scipy.stats.chisquare (SciPy 1.17.1), computed separately from the counting script. Expected count per permutation: 1,000,000.
| Permutation | sort(() => Math.random() - 0.5) | Fisher-Yates |
|---|---|---|
| 123 | 1,502,067 | 1,001,522 |
| 132 | 748,980 | 1,000,571 |
| 213 | 1,497,866 | 1,000,688 |
| 231 | 750,077 | 999,434 |
| 312 | 750,909 | 999,279 |
| 321 | 750,101 | 998,506 |
| chi-square (5 degrees of freedom) | 749,910 | 6.2 |
| p-value | below 1e-300 (the double underflows to 0) | 0.288 |
The sort version produces 123 and 213 about twice as often as the other four. The Fisher-Yates counts stay within 0.15% of the expected value, and a p-value of 0.288 is consistent with a fair shuffle.
Measured: 4 and 5 elements, 6,000,000 shuffles each
| Elements | Method | Chi-square | p-value | Highest count vs expected | Lowest count vs expected |
|---|---|---|---|---|---|
| 4 (24 permutations) | sort | 754,822 | below 1e-300 | +50.5% | -25.3% |
| 4 | Fisher-Yates | 31.1 (23 df) | 0.121 | +0.56% | -0.37% |
| 5 (120 permutations) | sort | 1,384,112 | below 1e-300 | +88.7% | -53.6% |
| 5 | Fisher-Yates | 103.7 (119 df) | 0.839 | +1.24% | -1.13% |
On these runs the skew of the sort method grows with the number of elements. A single Fisher-Yates run with a p-value of 0.12 or 0.29 is normal: with a fair shuffle the p-value is spread evenly between 0 and 1, so one lowish value does not prove a bug.
The off-by-one trap
A common variant swaps each element with a random index from the whole array instead of from 0..i:
for (let i = arr.length - 1; i >= 0; i--) {
const j = Math.floor(Math.random() * arr.length); // wrong: 0..n-1
[arr[i], arr[j]] = [arr[j], arr[i]];
}
For n = 3 there are 3 x 3 x 3 = 27 equally likely index sequences, and 27 cannot be split evenly across 6 permutations. Enumerating all 27 (Node and Python agree) gives:
| Permutation | 123 | 132 | 213 | 231 | 312 | 321 |
|---|---|---|---|---|---|---|
| Sequences producing it | 4 | 5 | 5 | 4 | 5 | 4 |
So 132, 213 and 312 are 25% more likely than the others (5/27 vs 4/27), by construction, no matter how good the random numbers are. For n = 4, 256 sequences go into 24 permutations: between 8 and 15 each instead of 10.67. Wikipedia calls this the "naive method" and says it is biased. The opposite mistake, picking j strictly below i, gives Sattolo's algorithm, where no element can stay in its original position, which is not a uniform shuffle either.
Modulo bias
Bias also appears when you turn random bits into an index with %. Take a random byte (0 to 255) and compute byte % 6 to roll a die. Since 256 = 6 x 42 + 4, the values 0 to 3 come up one extra time. Exact counts over all 256 byte values:
| Face (byte % 6) | 0 | 1 | 2 | 3 | 4 | 5 |
|---|---|---|---|---|---|---|
| Plain modulo | 43 | 43 | 43 | 43 | 42 | 42 |
| Rejection sampling (discard 252 to 255) | 42 | 42 | 42 | 42 | 42 | 42 |
Faces 0 to 3 are 43/42 as likely as faces 4 and 5. Wikipedia notes that the bias favours small remainders. The fix is rejection sampling: throw away values at or above the largest multiple of n that fits, and draw again.
For a 32-bit random number and a short list the same effect exists but is tiny, roughly n / 2^32 in relative terms (an estimate from the arithmetic, not a measurement), so about one part in a billion for 5 items. It matters for byte-sized or small-range generators and when n is large.
Shuffle with crypto.getRandomValues and rejection sampling
function randBelow(n) {
const limit = Math.floor(2 ** 32 / n) * n;
const buf = new Uint32Array(1);
do { crypto.getRandomValues(buf); } while (buf[0] >= limit);
return buf[0] % n;
}
function shuffle(arr) {
for (let i = arr.length - 1; i > 0; i--) {
const j = randBelow(i + 1);
[arr[i], arr[j]] = [arr[j], arr[i]];
}
return arr;
}
Run 600,000 times on [1,2,3] in Node 25.8: 123 = 100,047, 132 = 99,524, 213 = 100,098, 231 = 100,482, 312 = 99,985, 321 = 99,864 (chi-square 4.89, p = 0.429).
Is Math.random() good enough?
Math.floor(Math.random() * n) has no modulo step, and the Fisher-Yates results above used it. MDN says Math.random() returns a pseudo-random number in [0, 1) with approximately uniform distribution that you can scale to your range, and also that it does not provide cryptographically secure numbers and must not be used for anything related to security (MDN, Math.random()). For a card game, a playlist or a classroom draw it is a reasonable choice. Where a guessable result has a cost (raffles, tokens, keys), use crypto.getRandomValues as above.
Shuffling in Python
import random
items = [1, 2, 3, 4, 5]
random.shuffle(items) # in place, returns None
print(items) # e.g. [4, 3, 2, 1, 5]
secure = random.SystemRandom() # uses os.urandom
secure.shuffle(items)
shuffled = random.sample(items, k=len(items)) # new list, original untouched
The Python documentation says random.shuffle(x) shuffles the sequence in place, recommends sample(x, k=len(x)) for immutable sequences, and warns that the module's generators should not be used for security (use the secrets module for that). It also says that for a sequence longer than 2080 elements, most permutations can never be generated by the Mersenne Twister generator, because n! exceeds its period (Python docs, random). random.SystemRandom draws from the operating system, so it has no seed and is not reproducible. Python 3.11 removed the old optional random argument of shuffle.
Measured with Python 3.11.15: 600,000 shuffles of [1,2,3] with random.shuffle gave counts between 99,757 and 100,125 per permutation (chi-square 1.34, p = 0.931).
Quick answers
What is a shuffle? Rearranging items into a random order so that every possible order is equally likely. A shuffle that favours some orders is a biased shuffle.
Is Fisher-Yates good? Yes. With a uniform source of random integers it produces each of the n! orders with the same probability and takes O(n) time. The weak points are the random source and the index mapping, not the algorithm.
How do I shuffle a list? In code, use Fisher-Yates (random.shuffle in Python, the loop above in JavaScript). Without code, paste one item per line into the list randomizer. Its source swaps from the last index down using crypto.getRandomValues and picks each index with rejection sampling, which is the Fisher-Yates structure with the modulo bias removed.
Tested
- Node v25.8.0 (V8 14.1.146.11): 6,000,000 shuffles each of 3, 4 and 5 elements with
sort(() => Math.random() - 0.5)and with Fisher-Yates usingMath.floor(Math.random() * (i + 1)). Counts collected in Node, chi-square and p-values computed in Python 3.11.15 with SciPy 1.17.1. Only V8 was measured; no other engine was run. - Exhaustive enumeration of all index sequences for Fisher-Yates (n = 3 and 4: every permutation exactly once) and the off-by-one variant (n = 3: 27 sequences, counts 4 and 5), in Node and again in Python. Modulo-bias table computed over all 256 byte values.
crypto.getRandomValuesrejection-sampling version: 600,000 runs in Node.random.shuffleandrandom.SystemRandom().shufflerun in Python 3.11.15.- Not tested: browsers, other JavaScript engines, and timing benchmarks.
Sources
- Wikipedia, Fisher-Yates shuffle (history, Durstenfeld, Knuth, naive method, modulo bias, Sattolo).
- V8 blog, Getting things sorted in V8 (Timsort since V8 7.0).
- MDN, Math.random().
- Python documentation, random (
shuffle,SystemRandom, security warning).
Related tools
List Randomizer
Paste your items and shuffle them into a completely random order instantly.
Hours Calculator
Add start, end and break times for each day to see daily hours, weekly totals and overtime instantly.
Character Counter
Count characters, words, sentences, lines and UTF-8 bytes with live SEO and social media limit tracking.
Keyboard Test
Press any key to see it light up and find dead, stuck or double-typing keys, with rollover checks for full size, TKL and 75% layouts.
Written by Mian Ali Khalid. More guides in Dev Productivity.