{"id":177,"date":"2026-11-13T12:33:39","date_gmt":"2026-11-13T04:33:39","guid":{"rendered":"https:\/\/hoho.live\/luda\/index.php\/2026\/11\/13\/how-fisher-yates-shuffles-with-one-swap-per-index\/"},"modified":"2026-11-13T21:51:52","modified_gmt":"2026-11-13T13:51:52","slug":"how-fisher-yates-shuffles-with-one-swap-per-index","status":"publish","type":"post","link":"https:\/\/hoho.live\/luda\/index.php\/2026\/11\/13\/how-fisher-yates-shuffles-with-one-swap-per-index\/","title":{"rendered":"How Fisher-Yates shuffles with one swap per index"},"content":{"rendered":"\n<p class=\"wp-block-paragraph\"><strong>Short answer:<\/strong> The <strong>Fisher-Yates shuffle<\/strong>, in the modern inside-out or the usual in-place form, produces each permutation of an array with equal probability. The in-place loop walks i from the end down to 1 and swaps i with a uniformly chosen index j in 0..i, inclusive. That is <strong>n\u22121<\/strong> swaps and <strong>n\u22121<\/strong> random integers. A common bug chooses j in 0..n\u22121 at every i, which does not give a uniform permutation.<\/p>\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n<h4 class=\"wp-block-heading\"><strong>What the problem actually asks<\/strong><\/h4>\n\n<p class=\"wp-block-paragraph\">There are n! permutations. A shuffle is uniform when each of them has probability 1\/n!. The in-place loop builds the permutation from the back: the item placed at i is equally likely to be any of the items still in the prefix, including the one already there. The number of possible execution traces is n\u00b7(n\u22121)\u00b7\u2026\u00b71 = n!, and they are equally likely, so the distribution is exact.<\/p>\n\n\n<p class=\"wp-block-paragraph\">Choosing the swap partner from the whole array at every step produces n^n traces, which is not divisible by n! in a way that balances the permutations. Some orders come out more often than others. Sorting by random keys is uniform only when the keys do not tie, and it spends an unnecessary n log n.<\/p>\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n<h4 class=\"wp-block-heading\"><strong>What the algorithm guarantees<\/strong><\/h4>\n\n<p class=\"wp-block-paragraph\">With a uniform independent integer in 0..i at step i, every permutation has probability 1\/n!. Time is \u0398(n) after the random integers are available. Extra memory is none for the in-place form. The algorithm does not need floating-point random numbers. A biased remainder, when a random 32-bit word is reduced modulo i+1 by a plain remainder, slightly prefers small residues. The practical repair is rejection sampling or a wide multiply. For a teaching implementation the mathematical statement assumes a truly uniform index.<\/p>\n\n\n<p class=\"wp-block-paragraph\">The inside-out variant writes a new array and is the form to use when the source must stay intact. It has the same distribution.<\/p>\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n<h4 class=\"wp-block-heading\"><strong>The working steps<\/strong><\/h4>\n\n<ol class=\"wp-block-list\">\n<li>For i from n\u22121 down to 1, draw j uniformly from 0, 1, \u2026, i.<\/li>\n<li>Swap a[i] with a[j]. When j equals i the swap is a no-op and is a legal outcome.<\/li>\n<li>The index 0 is never the loop variable. It is already the last remaining item.<\/li>\n<li>Do not draw j from the whole array. The upper bound shrinks with i.<\/li>\n<li>To keep the source, for i from 0 to n\u22121 draw j in 0..i, set the new array&#8217;s i to the new array&#8217;s j, and set the new array&#8217;s j to source[i].<\/li>\n<\/ol>\n\n\n<p class=\"wp-block-paragraph\">Uniformity needs the shrinking range. A random-key sort is a different algorithm and pays for a comparison sort. Cryptographic shuffles need a cryptographic random source and the same index rule. The algorithm permutes an array. It does not sample a subset. Reservoir sampling does that.<\/p>\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n<h4 class=\"wp-block-heading\"><strong>Approaches that look simpler and fail<\/strong><\/h4>\n\n<figure class=\"wp-block-table\">\n<table>\n<thead>\n<tr>\n<th>Approach<\/th>\n<th>Why it fails when the swap index ignores the shrinking range<\/th>\n<\/tr>\n<\/thead>\n<tbody>\n<tr>\n<td>Draw j from 0..n\u22121 at every i<\/td>\n<td>The permutation is not uniform. Some orders are reachable by more traces than others.<\/td>\n<\/tr>\n<tr>\n<td>Draw j from 0..i\u22121, excluding i<\/td>\n<td>The item at i is forced to move. Permutations that fix i at that step are missing, and the last iterations cannot leave a prefix in place.<\/td>\n<\/tr>\n<tr>\n<td>Sort by random floating keys<\/td>\n<td>Ties, however rare, break the intended uniform draw, and the cost is n log n. The swap loop is linear and exact.<\/td>\n<\/tr>\n<tr>\n<td>Use a remainder of a random word without rejection<\/td>\n<td>The low residues are slightly more likely when the modulus does not divide the random range. The bias is small and is not the uniform model the proof uses.<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<\/figure>\n\n\n<p class=\"wp-block-paragraph\">A random subset of unknown length from a stream is reservoir sampling. A uniform permutation of an array in hand is Fisher-Yates. A random-key sort is unnecessary for this job.<\/p>\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n<h4 class=\"wp-block-heading\"><strong>A working example<\/strong><\/h4>\n\n<p class=\"wp-block-paragraph\">This Python fragment swaps index i with a uniform index in 0\u2026i, walking downward. The seeded permutation of 0 1 2 3 is <code>2 0 1 3<\/code>.<\/p>\n\n<pre><code class=\"language-python\">import random\nrng = random.Random(0)\na = [0, 1, 2, 3]\nfor i in range(len(a) - 1, 0, -1):\n    j = rng.randrange(i + 1)\n    a[i], a[j] = a[j], a[i]\nassert sorted(a) == [0, 1, 2, 3]\nprint(*a)\n<\/code><\/pre>\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n<h4 class=\"wp-block-heading\"><strong>Where it is used<\/strong><\/h4>\n\n<p class=\"wp-block-paragraph\"><strong>Fisher-Yates<\/strong> is the in-place shuffle in Python <code>random.shuffle<\/code> and in every card or playlist shuffle that is actually uniform. Each index swaps with one later index. A sort by random keys is a different shuffle and can collide.<\/p>\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n<h4 class=\"wp-block-heading\"><strong>When you can drop this algorithm<\/strong><\/h4>\n\n<p class=\"wp-block-paragraph\">Drop the full-range swap. Use the shrinking upper bound. Keep rejection sampling on the random source when the remainder bias matters.<\/p>\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n<h4 class=\"wp-block-heading\"><strong>Why this stays published<\/strong><\/h4>\n\n<p class=\"wp-block-paragraph\">We publish this so a search for Fisher-Yates returns the shrinking index range that makes every permutation equally likely. <strong>The Fisher-Yates shuffle swaps each index i with a uniform index in 0..i, which produces every permutation with probability 1\/n! in linear time.<\/strong><\/p>\n\n\n<p class=\"wp-block-paragraph\">\u672c\u6587\u7531 HoHo \u8207 AI \u5354\u4f5c\u6574\u7406\uff0c\u6700\u5f8c\u66f4\u65b0\u65bc 2026 \u5e74 11 \u6708 13 \u65e5\u3002<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Short answer: The Fisher-Yates shuffle, in the modern inside-out or the usual in-place form, produces each permutation of an array with equal probability. The in-place loop walks i from the end down to 1 and swaps i with a uniformly chosen index j in 0..i, inclusive. That is n\u22121&hellip;<\/p>\n","protected":false},"author":2,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[30,52],"tags":[],"class_list":["post-177","post","type-post","status-publish","format-standard","hentry","category-algorithms","category-randomization"],"_links":{"self":[{"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/posts\/177","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/users\/2"}],"replies":[{"embeddable":true,"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/comments?post=177"}],"version-history":[{"count":2,"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/posts\/177\/revisions"}],"predecessor-version":[{"id":576,"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/posts\/177\/revisions\/576"}],"wp:attachment":[{"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/media?parent=177"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/categories?post=177"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/tags?post=177"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}