The Fisher-Yates Shuffle

Matt George

Fractional CTO · Founder of Injuria.ai

•19 min read•

The Fisher-Yates shuffle is an algorithm for generating a random permutation of a finite sequence.[20] In mathematical terms, it provides a guarantee that every possible ordering of a given set of elements is equally likely to be produced Wolfram MathWorld[1]. The algorithm takes a list of distinct items and randomizes their order, a process equivalent to drawing numbered slips of paper from a hat without replacement until the hat is empty NIST Dictionary of Algorithms and Data Structures[2]. When implemented correctly with a high-quality source of randomness, the algorithm produces an unbiased permutation in linear time and constant space cppreference.com[3].

Originally developed in the late 1930s as a manual method for researchers needing random samples for agricultural and biological experiments, the procedure was later adapted for digital computers Fisher and Yates 1938. The modern algorithmic form, which operates in-place by swapping elements within an array, was published in the 1960s Durstenfeld 1964[4].[21] This optimized version requires exactly one random number generation and one swap operation per element, making it highly efficient. It avoids the quadratic time complexity that affected earlier naive shuffling methods, which often required shifting array elements or maintaining separate lists of unchosen items Knuth 1969[5].

Today, the algorithm is the standard method for shuffling data in software engineering.[22] It is embedded in the standard libraries of almost all major programming languages Python Software Foundation[6]. Despite its simplicity, implementing the shuffle correctly requires careful attention to the underlying pseudorandom number generator and the arithmetic used to select indices. Subtle errors in these areas routinely lead to biased outputs, making the mathematical properties and historical refinements of the algorithm a subject of continuous study in computer science MacLaren 1970[7].

Algorithmic Mechanism

The fundamental goal of a shuffling algorithm is to take a sequence of $n$ elements and return one of the $n!$ (n factorial) possible permutations, with each permutation having a probability of exactly $1/n!$ Wolfram MathWorld[1]. The Fisher-Yates shuffle achieves this by iteratively selecting an element from the pool of remaining unshuffled items and moving it to its final position NIST Dictionary of Algorithms and Data Structures[2].

In the original manual method, a researcher would write down the numbers from 1 to $n$. The researcher would then choose a random number $k$ between 1 and the number of remaining unstruck items. Counting through the unstruck numbers, the researcher would strike out the $k$-th available number and write it down in a new list Fisher and Yates 1938. This process repeated until all numbers were struck out. While mathematically sound, this manual counting process translates poorly to computer arrays. Finding the $k$-th unstruck item requires scanning the array from the beginning and counting only the items that have not yet been selected. In the worst case, the computer must scan $n$ items on the first draw, $n - 1$ on the second, and so forth. The sum of these operations is an arithmetic progression that evaluates to $n(n + 1)/2$, which results in a time complexity of $O(n^2)$ Knuth 1969[5].

The modern computer algorithm solves this inefficiency by dividing a single array into two logical sections: a shuffled section and an unshuffled section Durstenfeld 1964[4]. The algorithm iterates through the array from the last element down to the first. At each step $i$, the algorithm selects a random integer $j$ between 0 and $i$ (inclusive). It then swaps the element at index $i$ with the element at index $j$.[23] The element at index $i$ is now considered part of the shuffled section, and the unshuffled section shrinks by one cppreference.com[3].

for i from n - 1 down to 1 do
    j = random integer such that 0 <= j <= i
    exchange a[j] and a[i]

This in-place swapping mechanism guarantees that every element has an equal chance of ending up in any position. In the first iteration, an element is chosen from all $n$ elements and placed in the final position. In the second iteration, an element is chosen from the remaining $n - 1$ elements and placed in the second-to-last position. This continues until only one element remains, which by definition must stay in the first position Wolfram MathWorld[1].

To illustrate, consider an array containing the letters A, B, C, D, and E. The array has a length of 5. The algorithm begins at index 4 (the letter E). It generates a random number between 0 and 4. If the random number is 1, the algorithm swaps the element at index 1 (B) with the element at index 4 (E). The array becomes A, E, C, D, B. The letter B is now permanently in the final position. The algorithm then decrements the index to 3 (the letter D) and generates a random number between 0 and 3. If the random number is 3, the element at index 3 swaps with itself, leaving D in the fourth position. This process repeats until the index reaches 0, at which point the entire array is randomized.

Complexity and Mathematical Properties

The modern Fisher-Yates shuffle operates with a time complexity of $O(n)$, where $n$ is the number of elements in the array NIST Dictionary of Algorithms and Data Structures[2]. The loop executes exactly $n - 1$ times. Within each iteration, the algorithm performs a constant number of operations: generating a random integer, calculating an array index, and swapping two elements. Because these operations take $O(1)$ time, the overall execution time scales linearly with the size of the input cppreference.com[3].

The space complexity is $O(1)$ auxiliary space. The algorithm modifies the original array in-place, requiring only a few variables to store the loop counter, the random index, and a temporary value used during the swap operation Durstenfeld 1964[4]. No additional arrays or data structures are allocated, making it highly memory efficient.

A common optimization question is whether to skip the swap operation when the random index $j$ equals the current index $i$. While skipping the swap saves memory write operations, introducing a conditional branch often degrades performance on modern processors due to branch prediction failures[7]. A CPU pipeline attempts to predict the outcome of conditional statements to keep instructions flowing without interruption. Because the condition checking if $i$ equals $j$ is false most of the time but true randomly, the branch predictor will frequently guess incorrectly. These mispredictions cause pipeline flushes that consume significantly more clock cycles than a redundant memory write. Consequently, standard implementations perform the swap unconditionally, writing the element to its own memory location when $i$ equals $j$ Python Software Foundation[6].

Mathematical Proof of Uniformity

To rigorously prove that the Fisher-Yates shuffle generates every permutation with equal probability, one must analyze the probability of an element being placed in a specific position. Let the array have $n$ elements. During the first iteration, the algorithm selects an element from the $n$ available positions and places it at the final index, $n - 1$. The probability that any specific element is chosen for this position is exactly $1/n$ Knuth 1969[5].

During the second iteration, the algorithm selects from the remaining $n - 1$ elements and places the chosen element at index $n - 2$. The probability that a specific remaining element is chosen is $1/(n - 1)$. However, the unconditional probability that a specific element ends up at index $n - 2$ must account for the fact that it was not chosen in the first iteration. The probability it was not chosen in the first iteration is $(n - 1)/n$. Multiplying these probabilities yields $((n - 1)/n) \times (1/(n - 1)) = 1/n$ Wolfram MathWorld[1].

By mathematical induction, the probability that any element ends up in any specific position $k$ is always $1/n$. Because the choices are independent, the probability of any specific sequence of elements (a complete permutation) is the product of the probabilities of each independent choice. The first position is chosen from $n$ elements, the second from $n - 1$, down to the last position from 1 element. The total probability for a specific permutation is exactly $1 / (n \times (n - 1) \times \dots \times 1) = 1/n!$. This confirms that the distribution of permutations is perfectly uniform NIST Dictionary of Algorithms and Data Structures[2].

Discovery and Historical Development

Ronald A. Fisher was a British statistician and geneticist who made foundational contributions to the design of experiments. Working at the Rothamsted Experimental Station, Fisher developed the concept of randomization to avoid systematic errors in agricultural trials. If a researcher planted different crop varieties in a field, variations in soil fertility could skew the results. To prevent this, Fisher advocated for randomly assigning treatments to different plots. In 1938, Fisher and his colleague Frank Yates published "Statistical tables for biological, agricultural and medical research" Fisher and Yates 1938. This book provided researchers with pre-calculated tables of random digits, generated using a mechanized process, to facilitate this randomization. The authors included a specific algorithm for using these digits to shuffle a list of plots, which involved writing down the numbers 1 to $n$ and striking them out one by one based on the random digits.

This physical process was highly effective for human researchers but computationally inefficient for early computers. In 1964, Richard Durstenfeld, a programmer, recognized that the striking-out method required the computer to repeatedly scan the array to find the next available unstruck number. In a brief paper published in "Communications of the ACM", Durstenfeld introduced the swapping technique Durstenfeld 1964[4]. By moving the selected element to the end of the array and shrinking the effective size of the array by one, Durstenfeld eliminated the need for scanning. This reduced the time complexity from $O(n^2)$ to $O(n)$, a massive improvement for the slow processors and limited memory of the 1960s.

Donald E. Knuth, a computer scientist at Stanford University, cemented the algorithm's legacy in his seminal work, "The Art of Computer Programming". In Volume 2, published in 1969, Knuth presented the algorithm as "Algorithm P" and provided a comprehensive mathematical analysis of its behavior Knuth 1969[5]. Knuth explicitly credited Fisher and Yates for the conceptual foundation and Durstenfeld for the algorithmic optimization MacLaren 1970[7]. Because of Knuth's immense influence on the field of computer science, the algorithm is often referred to as the Knuth shuffle, though Knuth himself always maintained the attribution to Fisher, Yates, and Durstenfeld Wolfram MathWorld[1].

Common Implementation Errors

Despite the simplicity of the pseudocode, implementing the Fisher-Yates shuffle correctly requires precision. Small deviations from the standard algorithm often destroy the uniform distribution of permutations, leading to biased results Wolfram MathWorld[1].

The most common logical error is the naive shuffle, where the random index $j$ is chosen from the entire array (0 to $n - 1$) rather than the shrinking unshuffled portion (0 to $i$). This flawed approach results in $n^n$ possible sequences of random choices. Because $n^n$ is almost never evenly divisible by $n!$ (except when $n$ is 1 or 2), it is mathematically impossible for the naive shuffle to produce all permutations with equal probability Knuth 1969[5]. Some permutations will inevitably occur more frequently than others.

For an array of three elements (A, B, C), there are $3^3 = 27$ possible paths the naive algorithm can take, as it makes three independent choices from three options. However, there are only $3! = 6$ valid permutations of three elements. By the pigeonhole principle, because 27 is not evenly divisible by 6, the permutations cannot be distributed equally among the paths. Specifically, three permutations will be generated by five of the 27 paths (a probability of 5/27 or roughly 18.5 percent), while the other three permutations will be generated by only four paths (a probability of 4/27 or roughly 14.8 percent). This bias becomes exponentially worse as the array size increases.

Another frequent source of bias is the modulo operation used to scale the random number. Standard pseudorandom number generators (PRNGs) produce an integer within a specific range, typically 0 to a maximum value. To obtain a random number between 0 and $i$, programmers often use the modulo operator: rand() % (i + 1). If the maximum value of the PRNG is not a perfect multiple of $i + 1$, the lower numbers in the range will appear slightly more often than the higher numbers cppreference.com[8]. This phenomenon, known as modulo bias, skews the probability of the selected indices. High-quality implementations avoid modulo bias by using rejection sampling, which discards random numbers that fall outside the largest perfect multiple of the target range cppreference.com[3].

Pseudorandom Number Generators and Entropy

The Fisher-Yates shuffle is a deterministic algorithm; its randomness is entirely dependent on the quality of the random numbers provided to it. A pseudorandom number generator uses a mathematical formula to produce sequences of numbers that appear random but are actually determined by an initial value called a seed.

The state space of the underlying PRNG dictates the quality of the shuffle. A PRNG can only produce as many distinct sequences as its internal state allows. For example, a 32-bit PRNG has $2^{32}$ (approximately 4.29 billion) possible internal states. It can therefore generate at most 4.29 billion distinct permutations. However, a standard deck of 52 playing cards has 52! possible permutations, a number roughly equal to $8.06 \times 10^{67}$. Shuffling a deck of cards with a 32-bit PRNG guarantees that the vast majority of possible card orderings will never be generated Knuth 1969[5].

This limitation is a direct consequence of the pigeonhole principle. If a PRNG has fewer internal states than the number of possible permutations, it is mathematically impossible for the PRNG to generate every permutation. To achieve a truly uniform shuffle for an array of size $n$, the PRNG must possess at least $\log_2(n!)$ bits of internal state. For a 52-card deck, this requires a minimum of 226 bits of state.

Additionally, the concept of entropy is necessary when shuffling for cryptographic or high-stakes applications, such as online poker. Entropy refers to the measure of unpredictability in the random seed. If a PRNG is seeded with the current system time in milliseconds, an attacker who knows the approximate time the shuffle occurred can easily brute-force the seed, recreate the PRNG state, and predict the entire shuffled deck. To prevent this, secure applications use a cryptographically secure pseudorandom number generator (CSPRNG). A CSPRNG collects entropy from unpredictable hardware events, such as mouse movements, keyboard timing, or thermal noise in the CPU, to generate a seed that cannot be guessed NIST SP 800-90B[9]. The National Institute of Standards and Technology provides strict guidelines for these generators, ensuring that the random numbers fed into the Fisher-Yates shuffle are resilient against cryptographic attacks NIST SP 800-90A[10].

Cryptographic and Security Implications

When the Fisher-Yates shuffle is used in secure contexts, developers must account for side-channel attacks that can leak the internal state of the algorithm. The random swapping mechanism produces highly unpredictable memory access patterns. When shuffling very large arrays, these random accesses cause frequent cache misses. Each cache miss forces the processor to fetch data from main memory, which takes significantly longer than accessing the CPU cache.

An attacker sharing the same physical hardware (such as in a multi-tenant cloud environment) can use Prime+Probe techniques to observe which cache lines are accessed during the shuffle. By analyzing the timing of these cache misses, the attacker can deduce the sequence of swap indices, effectively reversing the shuffle without needing to compromise the PRNG seed[11].

To mitigate these vulnerabilities, cryptographic implementations often require constant-time variations that mask the swapping process. A constant-time shuffle ensures that the time taken to perform a swap does not depend on the indices involved, and it accesses memory in a deterministic pattern to prevent cache side-channels. However, achieving this level of security typically requires oblivious RAM (ORAM) techniques or sorting networks, which significantly increase the computational overhead from $O(n)$ to $O(n \log^2 n)$[12].[24]

Important Variants

Several variations of the Fisher-Yates shuffle have been developed to address specific use cases or mathematical requirements.

Sattolo's Algorithm

In 1986, Sandra Sattolo published "An algorithm to generate a random cyclic permutation" in the journal "Information Processing Letters" Sattolo 1986[13]. A cyclic permutation is a specific type of permutation consisting of a single cycle, meaning no element remains in its original position, and the entire set forms one continuous loop of displacements Wilson 2004[14].

Sattolo's algorithm modifies the Fisher-Yates shuffle by changing the range of the random index $j$. Instead of selecting $j$ from 0 to $i$ (inclusive), Sattolo's algorithm selects $j$ from 0 to $i - 1$ Sattolo 1986[13]. By preventing an element from being swapped with itself, the algorithm guarantees the generation of a single cycle of length $n$. There are $(n - 1)!$ possible cyclic permutations for a set of size $n$, and Sattolo's algorithm generates each with a uniform probability of $1/(n - 1)!$ Wilson 2004[14].

The Inside-Out Algorithm

The standard Fisher-Yates shuffle requires an existing, fully initialized array. The inside-out algorithm, also discussed by Knuth, combines the initialization and shuffling phases Knuth 1969[5]. It is used when a programmer needs to generate a shuffled array of the numbers 1 to $n$ from scratch.[25]

The algorithm iterates from 0 to $n - 1$. At each step $i$, it chooses a random index $j$ between 0 and $i$. If $j$ is not equal to $i$, the algorithm copies the value currently at index $j$ to index $i$. It then places the new value at index $j$. This approach builds the shuffled array dynamically, requiring the same $O(n)$ time complexity but avoiding a separate initialization loop Knuth 1969[5].

Parallel Shuffling

The strict sequential nature of the Fisher-Yates loop makes it difficult to parallelize. Each swap depends on the state of the array left by the previous swap, creating a loop-carried dependency. As multi-core processors became standard, researchers developed parallel random permutation algorithms to overcome this limitation Shun et al. 2015[15]. Methods such as the merge shuffle divide the array into smaller segments, assign each segment to a different processor thread, and shuffle them independently using the standard Fisher-Yates algorithm. Once the local shuffles are complete, the threads merge the segments using random interleaving Bacher et al. 2015[15]. While these parallel algorithms achieve lower latency on large datasets by utilizing multiple cores, they require $O(n)$ auxiliary space and complex thread synchronization. For most common applications, the standard sequential algorithm remains preferable due to its simplicity and zero memory overhead.

Real-World Applications

The Fisher-Yates shuffle is the foundational algorithm for randomization in modern software. It is implemented directly in the standard libraries of most programming languages.

In Python, the random.shuffle() function uses the Fisher-Yates algorithm Replit. The Python implementation relies on the Mersenne Twister PRNG, which has an internal state of 19937 bits Python Software Foundation[6]. This massive state space allows Python to uniformly shuffle arrays of up to 2080 elements without missing any permutations Stack Overflow[16]. The source code explicitly iterates backward through the list, swapping elements in-place Python Software Foundation[6]. The Mersenne Twister algorithm itself was designed specifically to resolve the state space limitations of older linear congruential generators Matsumoto and Nishimura 1998.

In Java, the java.util.Collections.shuffle() method implements the algorithm Baeldung[17]. If the provided list does not support fast random access (such as a linked list), the Java implementation first copies the elements into an array, shuffles the array in-place, and then copies the elements back into the list OpenJDK[18]. If the algorithm attempted to access elements in a linked list by their index, each access would require traversing the list from the head node to the target index. This traversal takes $O(k)$ time for the $k$-th element, causing the overall shuffle to degrade into $O(n^2)$ time complexity. By temporarily moving the data into a contiguous array, the Java implementation preserves the $O(n)$ performance guarantee regardless of the underlying collection type ZetCode. The method also allows developers to pass a custom Random object to ensure deterministic shuffling when needed Microsoft Learn[19].

In C++, the <algorithm> header provides std::shuffle cppreference.com[3]. The C++ standard explicitly requires the algorithm to operate in $O(n)$ time and swap elements uniformly based on the provided random number engine cppreference.com[8]. Earlier versions of C++ included a std::random_shuffle function, but it was deprecated in C++14 and removed in C++17 because it relied on the C standard library's rand() function, which often suffered from small state spaces and modulo bias cppreference.com[3].

In SQL databases, developers often attempt to shuffle query results using ORDER BY RAND(). This approach assigns a random number to every row in the table and then sorts the table based on those numbers. While this produces a random permutation, it requires $O(n \log n)$ time due to the sorting step, and it forces the database to perform a full table scan. A standard engineering practice is to query the primary keys, return them to the application layer, and use the Fisher-Yates shuffle in memory to randomize the data before fetching the full records. This highlights the algorithm's efficiency advantage over sorting-based randomization.

Significance and Tradeoffs

The primary significance of the Fisher-Yates shuffle is its mathematical optimality. It achieves the theoretical lower bounds for both time and space complexity while providing a perfect uniform distribution Wolfram MathWorld[1]. No algorithm can shuffle an array in less than $O(n)$ time, as every element must be visited at least once. Similarly, no algorithm can use less than $O(1)$ auxiliary space Knuth 1969[5].

Despite its optimality, the algorithm has limitations in modern computing environments. As discussed regarding side-channel attacks, the random memory access pattern is hostile to CPU caching architectures. For massive datasets that exceed the capacity of the cache, algorithms that optimize for memory locality, such as external memory sorting with random keys, may outperform the in-place Fisher-Yates shuffle in wall-clock time, even if their theoretical time complexity is higher Shun et al. 2015[15]. For general-purpose programming, however, the Fisher-Yates shuffle remains the definitive solution for generating random permutations Mena et al. 2024[11].

Sources (25)
  1. Wolfram MathWorld
  2. NIST Dictionary of Algorithms and Data Structures
  3. cppreference.com
  4. ACM Digital Library
  5. www-cs-faculty.stanford.edu: Knuth 1969
  6. Python Software Foundation
  7. MacLaren 1970
  8. cppreference.com
  9. NIST SP 800-90B
  10. NIST SP 800-90A
  11. Mena et al. 2024
  12. NIST SP 800-90C
  13. Sattolo 1986
  14. Wilson 2004
  15. ACM Digital Library
  16. Stack Overflow
  17. Baeldung
  18. OpenJDK
  19. Microsoft Learn
  20. Gregorio Martinez Perez, Sabu M. Thampi, Ryan Ko, Recent Trends in Computer Networks and Distributed Systems Security (Springer, 2014)
  21. Graham Cormode, Ke Yi, Small Summaries for Big Data (Cambridge University Press, 2020)
  22. Eric Lippert, Fabulous Adventures in Data Structures and Algorithms (Simon and Schuster, 2026)
  23. Wieland Fischer, Naofumi Homma, Cryptographic Hardware and Embedded Systems - CHES 2017 (Springer, 2017)
  24. Daniel Escudero, Ivan Damgård, Progress in Cryptology - LATINCRYPT 2025 (Springer Nature, 2025)
  25. Tanja Lange, Rainer Steinwandt, Post-Quantum Cryptography (Springer, 2018)

Recommended reading