TOPICS
Search

Fisher-Yates Shuffle


The Fisher-Yates shuffle is an algorithm for generating a random permutation of a list of n distinct elements. Starting with the elements a_1, a_2, ..., a_n, successively take i=n, n-1, ..., 2. At each step, choose j uniformly at random from 1, 2, ..., i and exchange a_i with a_j. An equivalent version proceeds from left to right, exchanging a_i with an element chosen uniformly from positions i through n.

There are i choices at step i, and every permutation corresponds to exactly one sequence of choices. Provided the choices are statistically independent and each has a uniform distribution, every permutation therefore has probability

 product_(i=2)^n1/i=1/(n!).

With a random-access array and constant-time generation of each random index, the algorithm runs in O(n) time and uses O(1) auxiliary space in big-O notation (Durstenfeld 1964, Knuth 1998, Eberl 2016).

Uniform selection of j from its stated range is essential. Reducing an integer-valued random quantity modulo a modulus i introduces bias unless its residue classes are equally likely, as does exchanging each element with an element chosen from the entire list at every step. The latter procedure is known as the exchange shuffle and does not in general produce a uniform random permutation.

The original procedure was introduced by Fisher and Yates (1938). The efficient in-place version above is due to Durstenfeld (1964). It is also known as the Knuth shuffle after Donald Knuth (Knuth 1998).


See also

Exchange Shuffle, Permutation, Random Permutation, Shuffle

Explore with Wolfram|Alpha

References

Black, P. E. "Fisher-Yates Shuffle." In "Dictionary of Algorithms and Data Structures." https://xlinux.nist.gov/dads/HTML/fisherYatesShuffle.html.Durstenfeld, R. "Algorithm 235: Random Permutation." Comm. ACM 7, 420, 1964. https://doi.org/10.1145/364520.364540.Eberl, M. "Fisher-Yates Shuffle." Archive of Formal Proofs, 2016. https://isa-afp.org/entries/Fisher_Yates.html.Fisher, R. A. and Yates, F. Statistical Tables for Biological, Agricultural and Medical Research. Edinburgh, Scotland: Oliver & Boyd, 1938.Knuth, D. E. §3.4.2 in The Art of Computer Programming, Vol. 2: Seminumerical Algorithms, 3rd ed. Reading, MA: Addison-Wesley, p. 145, 1998.

Cite this as:

Weisstein, Eric W. "Fisher-Yates Shuffle." From MathWorld--A Wolfram Resource. https://mathworld.wolfram.com/Fisher-YatesShuffle.html

Subject classifications