{
  "id": "fisher-yates-shuffle",
  "title": "Fisher–Yates shuffle",
  "lang": "en",
  "source_lang": "en",
  "summary": "The Fisher–Yates shuffle generates a uniformly random permutation of a finite sequence, using a linear-time, in-place procedure in its modern form.",
  "category": "computer-science",
  "subcategory": "algorithms-theory",
  "type": "concept",
  "aliases": [
    "Fisher–Yates algorithm",
    "Knuth shuffle",
    "Durstenfeld shuffle"
  ],
  "generated_at": "2026-11-05",
  "model": "pro/gpt-6.1-sol",
  "url": "https://aiwiki.page/en/fisher-yates-shuffle/",
  "translations": {
    "zh-Hans": {
      "url": "https://aiwiki.page/zh/fisher-yates-shuffle/",
      "json": "https://aiwiki.page/zh/fisher-yates-shuffle.json"
    }
  },
  "sections": [
    {
      "heading": "",
      "text": "The Fisher–Yates shuffle is a randomized algorithm for rearranging a finite sequence into a random order. Given \\(n\\) distinguishable elements, it produces each of the \\(n!\\) possible permutations with equal probability, provided that its random choices are unbiased and appropriately independent. Its modern implementation repeatedly swaps an element with a randomly chosen element from the portion not yet finalized, taking linear time and constant auxiliary space."
    },
    {
      "heading": "History",
      "text": "Ronald A. Fisher and Frank Yates described the original method in their 1938 book Statistical Tables for Biological, Agricultural and Medical Research. It was intended for use with tables of random numbers: repeatedly select an item uniformly from those remaining, record it, and remove it from further consideration.\n\nRichard Durstenfeld published a computer-oriented version in 1964. Instead of removing an item and shifting the remaining elements, this version exchanges the selected item with an element at the boundary of the unprocessed region. Donald Knuth subsequently presented the algorithm in The Art of Computer Programming, helping establish its widespread use.\n\n“Fisher–Yates shuffle” commonly refers to this modern, in-place version. The names “Durstenfeld shuffle” and “Knuth shuffle” also occur, although the historical contributions are distinct."
    },
    {
      "heading": "Modern algorithm",
      "text": "For a zero-indexed array \\(A\\) of length \\(n\\), the algorithm proceeds from the last position toward the first. At position \\(i\\), it chooses an integer \\(j\\) uniformly from the inclusive range \\(0\\) through \\(i\\), then swaps \\(A[i]\\) and \\(A[j]\\).\n\nIn pseudocode:\n\nfisher_yates(A):\n    n = length(A)\n    for i = n - 1 down to 1:\n        j = uniform_integer(0, i)\n        swap(A[i], A[j])\n\nHere, uniform_integer(0, i) must include both endpoints. Choosing \\(j=i\\), and therefore leaving the current element in place, is a necessary part of the algorithm.\n\nAfter each iteration, position \\(i\\) contains its final element. Later iterations operate only on positions below it. Arrays of length zero or one require no swaps.\n\nAn equivalent forward version visits \\(i=0,\\ldots,n-2\\), choosing \\(j\\) uniformly from \\(i,\\ldots,n-1\\). Both forms work by selecting uniformly from the remaining elements and shrinking the unprocessed region."
    },
    {
      "heading": "Why the result is uniform",
      "text": "The correctness argument can be expressed as a loop invariant: before each selection, the unprocessed region contains exactly the elements not yet assigned to finalized positions.\n\nConsider any particular target arrangement of \\(n\\) distinct elements:\n\n- Its required last element is selected with probability \\(1/n\\).\n- Conditional on that selection, its required next-to-last element is selected with probability \\(1/(n-1)\\).\n- This continues until the last remaining element is determined.\n\nThus the probability of obtaining that target arrangement is\n\n\\[\\frac{1}{n}\\cdot\\frac{1}{n-1}\\cdots\\frac{1}{2} =\\frac{1}{n!}.\\]\n\nBecause this holds for every permutation, the output has a uniform probability distribution over all permutations.\n\nEquivalently, the sequence of random index choices has\n\n\\[n(n-1)\\cdots 2=n!\\]\n\npossible outcomes. Each choice sequence corresponds to exactly one output permutation, and every choice sequence has the same probability.\n\nRepeated values\n\nThe proof treats input elements as distinguishable objects. If several elements have the same visible value, their identities can still be regarded as distinct during the shuffle.\n\nFor multiplicities \\(m_1,\\ldots,m_k\\), each distinct visible arrangement corresponds to \\(\\prod_{r=1}^{k}m_r!\\) labeled permutations. Consequently, every distinct visible arrangement also has equal probability:\n\n\\[\\Pr(\\text{a particular visible arrangement}) =\\frac{\\prod_{r=1}^{k}m_r!}{n!}.\\]\n\nRepeated values therefore do not invalidate the uniformity guarantee."
    },
    {
      "heading": "Computational cost",
      "text": "The modern algorithm performs \\(n-1\\) iterations and at most \\(n-1\\) swaps. Assuming constant-time random array access, swapping, and bounded-integer generation, its time complexity is \\(O(n)\\), and its auxiliary space complexity is \\(O(1)\\).\n\nThese assumptions matter:\n\n- A linked list does not generally support constant-time access by index, so directly applying the array implementation can take quadratic time.\n- The original selection-and-removal method can take \\(O(n^2)\\) time when each removal shifts the remaining array elements.\n- Swapping large records may cost more than swapping fixed-size values or references.\n- Producing unbiased bounded integers has its own computational and randomness costs.\n\nThe shuffle is therefore described as linear-time primarily in the usual array-based model of computational complexity."
    },
    {
      "heading": "Random-number generation and implementation pitfalls",
      "text": "The mathematical algorithm is unbiased, but an implementation inherits limitations from its random-number source and its method of generating bounded integers.\n\nModulo bias\n\nSuppose a random integer \\(X\\) is uniform over \\(0,\\ldots,M-1\\). Computing\n\n\\[j=X\\bmod b\\]\n\ndoes not generally produce a uniform integer in \\(0,\\ldots,b-1\\). It is uniform only when \\(b\\) divides \\(M\\); otherwise, some remainders occur more frequently than others.\n\nA standard remedy is rejection sampling. Define\n\n\\[L=M-(M\\bmod b).\\]\n\nDraw \\(X\\) repeatedly until \\(X<L\\), then return \\(X\\bmod b\\). The accepted range contains an equal number of representatives of every remainder. This construction assumes \\(1\\leq b\\leq M\\); larger bounds require a larger random range or another method.\n\nFloating-point scaling\n\nComputing \\(\\lfloor bU\\rfloor\\) is mathematically correct if \\(U\\) is an ideal continuous uniform random variable on \\([0,1)\\). Actual computer generators produce values from a finite set, so scaling can introduce bias or make some indices unreachable, especially for large bounds. Rounding instead of taking the floor can introduce additional errors.\n\nPseudorandom generators and seeds\n\nMost implementations use a pseudorandom number generator. A fixed seed produces a deterministic sequence and, with a fixed implementation, a repeatable shuffle.\n\nUniformity of the abstract algorithm does not establish that a particular generator can reach every permutation. If the generator has only \\(S\\) possible initial states, a deterministic shuffle driven solely by those states can produce at most \\(S\\) distinct outputs. Thus \\(S\\geq n!\\) is necessary, but not sufficient, for all permutations to be reachable.\n\nLikewise, individually uniform index choices are not enough if correlations between successive choices change their joint distribution. The proof requires each selection to be uniform conditional on the preceding choices.\n\nFor applications involving cryptography or adversarial prediction, uniformity and unpredictability are separate requirements. Fisher–Yates does not make a predictable random source secure, and it does not by itself establish the fairness of a larger protocol.\n\nIncorrect index ranges\n\nA common incorrect approach swaps each position with a random position anywhere in the full array. Earlier placements can then be disturbed, and the resulting permutation is generally biased.\n\nFor example, an implementation that makes three independent choices among all three positions has \\(3^3=27\\) equally likely choice sequences. These cannot be divided equally among the \\(3!=6\\) permutations.\n\nExcluding the current position is also incorrect for an ordinary Fisher–Yates shuffle. It prevents some outputs, including the unchanged arrangement for two elements."
    },
    {
      "heading": "Variants and related algorithms",
      "text": "Inside-out shuffle\n\nThe inside-out variant constructs a shuffled output array while processing the input from left to right:\n\ninside_out(input):\n    allocate output with length(input) positions\n    for i = 0 to length(input) - 1:\n        j = uniform_integer(0, i)\n        if j != i:\n            output[i] = output[j]\n        output[j] = input[i]\n    return output\n\nAt each step, the new element is inserted into a uniformly selected position, and any displaced element moves to the newly created position. This produces a uniform permutation without modifying the input, but requires \\(O(n)\\) output space.\n\nPartial shuffle and sampling\n\nWhen only \\(k\\) randomly selected elements are required, a forward Fisher–Yates shuffle can stop after finalizing its first \\(k\\) positions. Those positions form a uniformly random ordered sample without replacement. Ignoring their order gives a uniformly random \\(k\\)-element subset.\n\nWith a mutable, random-access input array, this requires \\(O(k)\\) swaps. For streams or inputs whose size is not known in advance, reservoir sampling addresses a different access model.\n\nSattolo’s algorithm\n\nSattolo’s algorithm resembles the backward shuffle but chooses \\(j\\) from \\(0,\\ldots,i-1\\), excluding \\(i\\). It generates permutations consisting of a single cycle rather than all permutations.\n\nIt is not a general-purpose substitute for Fisher–Yates. For more than one element, a single-cycle permutation has no fixed points, but not every fixed-point-free permutation consists of one cycle.\n\nRandom-key sorting\n\nAnother approach assigns random keys to elements and applies a sorting algorithm. With independent continuous keys and no ties, the resulting order is uniform. Finite keys introduce ties whose handling can affect the distribution, and comparison sorting generally takes \\(O(n\\log n)\\) time.\n\nUsing a comparator that returns random comparison results is different from sorting by fixed random keys. Such a comparator need not define a consistent ordering and can violate the sorting routine’s requirements."
    },
    {
      "heading": "Applications and testing",
      "text": "Fisher–Yates is used for virtual card decks, randomized experimental orders, simulation inputs, and the reordering of training data in machine learning. Its guarantee concerns the order of the supplied elements; it does not ensure that those elements were collected or selected without bias.\n\nTests can check that the output preserves the input’s elements and multiplicities, handles boundary cases, and behaves reproducibly under a fixed generator configuration. For very small arrays, enumerating all possible index-choice sequences can verify that every permutation occurs equally often.\n\nStatistical tests can detect some implementation errors, but equal frequencies for individual element positions do not prove that complete permutations are uniform. Correlations between positions may remain even when every element appears equally often in every position."
    }
  ],
  "links": [
    "randomized-algorithm",
    "permutation",
    "array-data-structure",
    "pseudocode",
    "loop-invariant",
    "probability",
    "probability-distribution",
    "time-complexity",
    "space-complexity",
    "linked-list",
    "computational-complexity",
    "pseudorandom-number-generator",
    "cryptography",
    "sorting-algorithm",
    "training-data",
    "machine-learning"
  ],
  "sources": [],
  "license": "https://creativecommons.org/licenses/by/4.0/"
}