# 费雪–耶茨洗牌

**费雪–耶茨洗牌**（Fisher–Yates shuffle）是一种算法，用于随机排列一个有限序列，使得在假定随机源公平的前提下，每一种可能的顺序、每一种排列都以完全相同的概率出现。它原地、线性时间运行，每个位置只访问一次，对于 \( N \) 个元素消耗 \( \Theta(N \log N) \) 个随机比特。<sup>[1](https://xlinux.nist.gov/dads/HTML/fisherYatesShuffle.html)</sup><sup> • </sup><sup>[2](https://raw.org/book/algorithms/fisher-yates-shuffle/)</sup> 今天使用的计算机版本也称为克努斯洗牌（Knuth shuffle）。

| 关键事实 | 详情 |
|---|---|
| 功能 | 通过将每个元素 \( e_i \) 与从位置 \( i \) 到 \( N \) 中的一个随机元素交换，随机排列 \( N \) 个元素；在公平随机源下，所有排列等可能<sup>[1](https://xlinux.nist.gov/dads/HTML/fisherYatesShuffle.html)</sup> |
| 成本 | 线性时间；消耗 \( \Theta(N \log N) \) 个随机比特；每次交换除一个临时变量外无需额外内存<sup>[1](https://xlinux.nist.gov/dads/HTML/fisherYatesShuffle.html)</sup><sup> • </sup><sup>[2](https://raw.org/book/algorithms/fisher-yates-shuffle/)</sup> |
| 起源 | 罗纳德·费雪（Ronald Fisher）和弗兰克·耶茨（Frank Yates）于 1938 年在《统计表》（*Statistical Tables*）中发表的纸笔流程<sup>[2](https://raw.org/book/algorithms/fisher-yates-shuffle/)</sup> |
| 现代形式 | 理查德·杜斯滕费尔德（Richard Durstenfeld），《算法 235：随机排列》（"Algorithm 235: Random permutation"），《ACM通讯》（*Communications of the ACM*）7(7):420，1964 年 7 月<sup>[3](https://cir.nii.ac.jp/crid/1363951795353481344)</sup> |
| 标准形式 | 克努斯（Knuth）《计算机程序设计艺术》（*The Art of Computer Programming*）中的算法 3.4.2P，因此得名克努斯洗牌<sup>[1](https://xlinux.nist.gov/dads/HTML/fisherYatesShuffle.html)</sup><sup> • </sup><sup>[2](https://raw.org/book/algorithms/fisher-yates-shuffle/)</sup> |
| 库中的存在 | Java 的 `Collections.shuffle`、Python 的 `random.shuffle` 和 Go 的 `rand.Shuffle` 都实现了它<sup>[4](https://docs.oracle.com/javase/tutorial/collections/interfaces/list.html)</sup><sup> • </sup><sup>[5](https://github.com/python/cpython/blob/main/Lib/random.py)</sup><sup> • </sup><sup>[6](https://go.dev/blog/randv2)</sup> |
| 主要陷阱 | 随机索引边界上的差一错误会把它变成萨托洛算法（Sattolo's algorithm），后者只产生单循环排列<sup>[7](https://arxiv.org/abs/2501.06084)</sup> |

## 算法如何工作

给定一个包含 \( n \) 个元素、索引为 \( 0, \dots, n-1 \) 的数组 \( a \)，现代算法从末尾向前处理各个位置。对于从 \( n-1 \) 递减到 1 的每个位置 \( i \)，它从 \( 0 \) 到 \( i \) 中均匀抽取一个随机整数 \( j \)，并交换 \( a[i] \) 与 \( a[j] \)。<sup>[2](https://raw.org/book/algorithms/fisher-yates-shuffle/)</sup> 美国国家标准与技术研究院（NIST）在 SP 800-90B 中的伪代码以从 1 开始的形式陈述同一循环：对于从 \( L \) 递减到 1 的 \( i \)，生成一个满足 \( 1 \leq j \leq i \) 的随机整数 \( j \)，并交换 \( s_j \) 与 \( s_i \)。<sup>[8](https://nvlpubs.nist.gov/nistpubs/SpecialPublications/nist.sp.800-90b.pdf)</sup>

将 \( j \) 限制在尚未洗牌的前缀内，正是算法无偏的原因：\( n! \) 种排列中的每一种都恰好由一条等可能的选值序列到达，因此没有任何排列受到偏爱。<sup>[9](https://quantmemo.com/concepts/biased-naive-shuffles)</sup> NIST 的《算法与数据结构词典》（Dictionary of Algorithms and Data Structures）指出，该算法可以看作一种反向选择排序。<sup>[1](https://xlinux.nist.gov/dads/HTML/fisherYatesShuffle.html)</sup>

## 历史

罗纳德·费雪和[弗兰克·耶茨](https://www.edgepedia.org/zh/frank-yates)在 1938 年的《统计表》一书中首次描述了这一技术，作为一种手工、纸笔方法，旨在帮助抽取随机样本。他们的版本反复搜索一个不断缩小的剩余元素列表。<sup>[2](https://raw.org/book/algorithms/fisher-yates-shuffle/)</sup> 当时在圣迭戈（San Diego）通用原子公司（General Atomic）任职的理查德·杜斯滕费尔德，在 1964 年 7 月的《ACM通讯》上以《算法 235：随机排列》为题发表了单趟原地版本。<sup>[3](https://cir.nii.ac.jp/crid/1363951795353481344)</sup> 唐纳德·克努斯（Donald Knuth）后来在《计算机程序设计艺术》中作为过程 3.4.2P 推广了该算法，这就是现代形式也称为克努斯洗牌的原因。<sup>[1](https://xlinux.nist.gov/dads/HTML/fisherYatesShuffle.html)</sup><sup> • </sup><sup>[2](https://raw.org/book/algorithms/fisher-yates-shuffle/)</sup>

## 为什么朴素洗牌有偏

一种常见的错误变体在每一步都从整个数组中抽取随机索引 \( j \)，而不是从尚未洗牌的前缀中抽取。这会过度计算某些顺序：通向不同排列的执行路径数量不相等，因此输出分布是有偏的。<sup>[9](https://quantmemo.com/concepts/biased-naive-shuffles)</sup> 一个相关错误是用一个每次调用都返回新随机值的比较器，按附加的随机键对元素排序；这样的比较器可能违反正确排序所依赖的传递性，于是输出分布取决于排序算法的内部行为，而不是仅取决于随机性。<sup>[2](https://raw.org/book/algorithms/fisher-yates-shuffle/)</sup>

实现错误在实践中很重要。\( j \) 的边界上一个简单的差一错误会把[算法](https://www.edgepedia.org/zh/algorithm)变成萨托洛算法，后者只产生具有单个循环的排列，而这类缺陷可能使在线彩票或扑克发生偏斜。<sup>[7](https://arxiv.org/abs/2501.06084)</sup>

## 随机性要求

该算法的无偏程度只取决于其随机索引生成器。生成指定范围内的整数时必须没有统计偏差；标准做法是使用拒绝采样，生成一个随机字，并拒绝那些会使某些余数占优的值。<sup>[10](https://arxiv.org/abs/1805.10941)</sup> 进一步的限制是生成器状态：即使元素数量相当少，排列总数也远远大于大多数伪随机数生成器的周期，这意味着大多数排列永远不会被生成。<sup>[1](https://xlinux.nist.gov/dads/HTML/fisherYatesShuffle.html)</sup> 对于密码学用途，Python 的文档指引用户使用 `secrets` 模块而不是 `random` 模块，后者的[梅森旋转算法](https://www.edgepedia.org/zh/mersenne-twister)（Mersenne Twister）核心是确定性的，不适合安全用途。<sup>[11](https://docs.python.org/3.11/library/random.html?highlight=shuffle)</sup>

## 标准库中的实现

**Java.** `Collections.shuffle` 以相反顺序遍历列表，从最后一个元素开始，到第二个元素结束；每一步它从第一个元素到当前元素的范围中随机选取一个元素，并将其交换到正在处理的位置。它恰好需要 `list.size()-1` 次交换，并以线性时间运行；如果列表没有实现 `RandomAccess` 且规模很大，该实现会在洗牌前把列表转储到数组中，以避免顺序访问列表的二次方行为。<sup>[4](https://docs.oracle.com/javase/tutorial/collections/interfaces/list.html)</sup><sup> • </sup><sup>[12](https://docs.oracle.com/en/java/javase/22/docs/api/java.base/java/util/Collections.html)</sup>

**Python.** CPython 的 `random.shuffle` 运行同样的反向循环，用 `randbelow(i + 1)` 抽取 \( j \)，并在 \( i \) 遍历反向范围时交换 `x[i]` 与 `x[j]`。<sup>[5](https://github.com/python/cpython/blob/main/Lib/random.py)</sup>

**Go.** Go 运行时在 `rand.Shuffle` 内采用了丹尼尔·勒米尔（Daniel Lemire）的避免除法的范围随机整数优化；Go 作者报告，这比 OpenBSD 风格的拒绝采样方法快 30%。<sup>[6](https://go.dev/blog/randv2)</sup><sup> • </sup><sup>[10](https://arxiv.org/abs/1805.10941)</sup>

## 应用

部分费雪–耶茨洗牌在处理完 \( N \) 个位置中的 \( M \) 个后停止，可产生简单随机无放回抽样；英特尔（Intel）oneMKL 的示例手册使用这种形式及其随机数生成器，从规模为 \( N \) 的总体中抽取长度为 \( M \) 的样本。<sup>[13](https://www.intel.com/content/www/us/en/docs/onemkl/cookbook/2023-2/multi-simple-random-sampling-without-replacement.html)</sup> NIST 的 SP 800-90B 在排列检验中使用该洗牌的伪代码，这些检验检查熵源是否产生独立同分布样本。<sup>[8](https://nvlpubs.nist.gov/nistpubs/SpecialPublications/nist.sp.800-90b.pdf)</sup> 在格式保留令牌化中，当可能的短输入数量 \( r^{\ell} \) 低于 1,000,000 时，对完整值表进行费雪–耶茨洗牌定义了加密映射，而该方法的安全性取决于洗牌是否均匀随机。<sup>[7](https://arxiv.org/abs/2501.06084)</sup>

由于该算法简短但很容易在细微处出错，它也成了形式验证的基准案例：泽奇（Zetzsche）、特里斯坦（Tristan）、勒普安特（Lepoint）和迈尔（Mayer）于 2025 年在 Dafny 中验证了其正确性，证明了一个函数式模型在所有排列上均匀分布，并证明了一个命令式数组实现与该模型等价。<sup>[7](https://arxiv.org/abs/2501.06084)</sup>

## References

1. [Paul E. Black, "Fisher-Yates shuffle", Dictionary of Algorithms and Data Structures, NIST, 5 April 2023](https://xlinux.nist.gov/dads/HTML/fisherYatesShuffle.html)
2. [Robert Eisele, "Introduction to the Fisher-Yates Shuffle", raw.org](https://raw.org/book/algorithms/fisher-yates-shuffle/)
3. [Richard Durstenfeld, "Algorithm 235: Random permutation", Communications of the ACM 7(7):420, July 1964](https://cir.nii.ac.jp/crid/1363951795353481344)
4. [The List Interface, The Java Tutorials, Oracle](https://docs.oracle.com/javase/tutorial/collections/interfaces/list.html)
5. [cpython/Lib/random.py, Python source repository](https://github.com/python/cpython/blob/main/Lib/random.py)
6. [Evolving the Go Standard Library with math/rand/v2, The Go Blog](https://go.dev/blog/randv2)
7. [Stefan Zetzsche, Jean-Baptiste Tristan, Tancrede Lepoint, Mikael Mayer, "Verifying the Fisher-Yates Shuffle Algorithm in Dafny", arXiv:2501.06084 (2025)](https://arxiv.org/abs/2501.06084)
8. [NIST SP 800-90B, Recommendation for the Entropy Sources Used for Random Bit Generation](https://nvlpubs.nist.gov/nistpubs/SpecialPublications/nist.sp.800-90b.pdf)
9. [Why the Naive Shuffle Is Biased, Quant Memo](https://quantmemo.com/concepts/biased-naive-shuffles)
10. [Daniel Lemire, "Fast Random Integer Generation in an Interval", arXiv:1805.10941 (2018)](https://arxiv.org/abs/1805.10941)
11. [random — Generate pseudo-random numbers, Python 3.11 documentation](https://docs.python.org/3.11/library/random.html?highlight=shuffle)
12. [Collections (Java SE 22 & JDK 22), Oracle](https://docs.oracle.com/en/java/javase/22/docs/api/java.base/java/util/Collections.html)
13. [Multiple simple random sampling without replacement, Intel oneMKL Cookbook](https://www.intel.com/content/www/us/en/docs/onemkl/cookbook/2023-2/multi-simple-random-sampling-without-replacement.html)

---
*Initially written Sep 17, 2026 · Reviewed: Oct 15, 2026 · Edited: Oct 15, 2026 · Last review: Oct 15, 2026*

Topic: 技术与人造世界 › 计算技术与数字系统 › 人工智能与数据 › Algorithms and computational methods › Numerical, string, and geometric algorithms › Pseudorandomness and hashing algorithms

Copyright 2026 Edgepedia

License: Edgepedia Community License 1.0, https://www.edgepedia.org/edgepedia/license

Source: https://www.edgepedia.org/zh/fisher-yates-shuffle

English original: https://www.edgepedia.org/fisher-yates-shuffle
