The Fisher?Yates Shuffle: Uniform Indices and Biased Sort Comparators

Shuffling a list of items—whether a playlist of songs, a deck of cards, a randomized quiz, or an activity suggestion generator—is a universal requirement across web applications. Yet, in modern JavaScript codebases, a dangerously flawed snippet continues to circulate as standard practice:

// DANGEROUS ANTI-PATTERN: Biased, non-uniform distribution
array.sort(() => Math.random() - 0.5);

A random sort comparator can produce biased permutations because it does not provide a consistent ordering. This guide shows Fisher–Yates as an alternative, with uniformity conditional on uniform index selection. The examples are standalone and should not be read as a claim that BoredNoMore currently uses this shuffle.

1. The Definition of an Unbiased Shuffle

From combinatorial mathematics, an array of n distinct elements possesses exactly n! (n factorial) possible permutations. For example, an array of 3 elements [A, B, C] has 3! = 6 permutations:

A shuffling algorithm is defined as unbiased (or fair) if and only if every single one of the n! permutations has an exact, equal probability of occurring:

P(permutation) = 1 / n!

Observed frequencies fluctuate in finite samples. A biased algorithm may give some permutations higher probability, but no short random run is expected to contain exactly equal counts.

2. Why Array.sort(() => Math.random() - 0.5) is Broken

Sorting algorithms (such as Timsort in V8, or Quicksort in older engines) are designed under the mathematical assumption that comparison functions are transitive:

When you pass () => Math.random() - 0.5, the comparator produces inconsistent, non-transitive results. In one comparison, it reports that A is less than B; on the next step, it reports that B is less than C, but C is less than A! The sorting algorithm's branch prediction and pivot selections break down.

Empirical Proof: The 100,000-Trial Test

Run repeated shuffles of [1, 2, 3] and count the six possible outputs to investigate bias in your browser. Exact frequencies depend on the engine and run. No fixed numerical outcome is asserted here.

3. The Fisher-Yates (Knuth) Shuffle

In 1938, Ronald Fisher and Frank Yates published a pen-and-paper algorithm for generating random permutations. In 1964, computer scientist Richard Durstenfeld modernized it for computers into an optimal, in-place algorithm popularized by Donald Knuth in The Art of Computer Programming.

The Algorithm Mechanics

The Fisher-Yates shuffle operates from the end of the array to the beginning:

  1. Start with index i pointing to the last element of the array (i = n - 1).
  2. Pick a random index j such that 0 <= j <= i.
  3. Swap the element at index i with the element at index j.
  4. Decrement i by 1 and repeat until reaching the first element.

Because each slot i is assigned an element chosen uniformly from the remaining unplaced elements, every element has an exact 1/n probability of landing in any given position. The total number of outcomes is n * (n - 1) * ... * 1 = n!, precisely matching the theoretical permutation count.

4. JavaScript Implementation: Optimal & In-Place

Below is the modern ES6 implementation of the Durstenfeld-Knuth variation using destructuring swap syntax:

function shuffleArray(array) {
    // Clone array if immutability is desired: const arr = [...array];
    const arr = array.slice();

    for (let i = arr.length - 1; i > 0; i--) {
        // Generate uniform integer in range [0, i]
        const j = Math.floor(Math.random() * (i + 1));

        // In-place ES6 swap
        [arr[i], arr[j]] = [arr[j], arr[i]];
    }

    return arr;
}

This implementation runs in strict O(n) time complexity (performing exactly n - 1 swaps) and O(1) auxiliary space complexity if executed directly on the source array. Unlike Array.prototype.sort() which executes in O(n log n) time, Fisher-Yates is both computationally faster and mathematically pure.

5. Cryptographically Sound Shuffling

In applications where money, prizes, or competitive gaming are involved (such as a lottery draw or poker hand distribution), using Math.random() inside Fisher-Yates introduces PRNG predictability. Replacing Math.random() with the Web Cryptography API provides a stronger random source; correct range mapping and the surrounding application still matter:

function secureShuffle(array) {
    const arr = array.slice();
    const buffer = new Uint32Array(1);

    for (let i = arr.length - 1; i > 0; i--) {
        // Rejection sampling for uniform range [0, i]
        const maxValid = Math.floor(4294967296 / (i + 1)) * (i + 1);
        let rand;
        do {
            window.crypto.getRandomValues(buffer);
            rand = buffer[0];
        } while (rand >= maxValid);

        const j = rand % (i + 1);
        [arr[i], arr[j]] = [arr[j], arr[i]];
    }

    return arr;
}

Conclusion

Software engineering is filled with seemingly harmless shortcuts that harbor severe algorithmic bugs. Shuffling via .sort(() => Math.random() - 0.5) is one of the most pervasive anti-patterns in web development. By adopting the linear-time Fisher-Yates shuffle, developers ensure that every user receives an authentic, fair, and statistically uniform experience.

For activity suggestions, try BoredNoMore. Its recommendation behavior is separate from the standalone shuffle examples above.

References

Sudarshan Babar

Sudarshan Babar

Founder & Lead Developer at getinfotoyou. Specialized in full-stack web architecture, client-side algorithm engineering, and transparent personal finance modeling.