计数排序
前置知识:前缀和
提醒
本页面要介绍的不是 基数排序。
本页面将简要介绍计数排序。
定义
计数排序(英语:Counting sort)是一种线性时间的排序算法。
过程
计数排序的工作原理是使用一个额外的数组 𝐶
,其中第 𝑖
个元素是待排序数组 𝐴
中值等于 𝑖
的元素的个数,然后根据数组 𝐶
来将 𝐴
中的元素排到正确的位置。
它的工作过程分为三个步骤:
- 计算每个数出现了几次;
- 求出每个数出现次数的 前缀和;
- 利用出现次数的前缀和,从右至左计算每个数的排名。
计算前缀和的原因
直接将 𝐶
中正数对应的元素依次放入 𝐴
中不能解决元素重复的情形。
我们通过为额外数组 𝐶
中的每一项计算前缀和,结合每一项的数值,就可以为重复元素确定一个唯一排名:
额外数组 𝐶
中每一项的数值即是该 key 值下重复元素的个数,而该项的前缀和即是排在最后一个的重复元素的排名。
如果按照 𝐴
的逆序进行排列,那么显然排序后的数组将保持 𝐴
的原序(相同 key 值情况下),也即得到一种稳定的排序算法。

性质
稳定性
计数排序是一种稳定的排序算法。
时间复杂度
计数排序的时间复杂度为 𝑂(𝑛 +𝑤)
,其中 𝑤
代表待排序数据的值域大小。
代码实现
伪代码
1𝐈𝐧𝐩𝐮𝐭. An array 𝐴 consisting of 𝑛 positive integers no greater than 𝑤.2𝐎𝐮𝐭𝐩𝐮𝐭. Array 𝐴 after sorting in nondecreasing order stably.3𝐌𝐞𝐭𝐡𝐨𝐝. 4𝐟𝐨𝐫 𝑖←0 𝐭𝐨 𝑤5𝑐𝑛𝑡[𝑖]←06𝐟𝐨𝐫 𝑖←1 𝐭𝐨 𝑛7𝑐𝑛𝑡[𝐴[𝑖]]←𝑐𝑛𝑡[𝐴[𝑖]]+18𝐟𝐨𝐫 𝑖←1 𝐭𝐨 𝑤9𝑐𝑛𝑡[𝑖]←𝑐𝑛𝑡[𝑖]+𝑐𝑛𝑡[𝑖−1]10𝐟𝐨𝐫 𝑖←𝑛 𝐝𝐨𝐰𝐧𝐭𝐨 111𝐵[𝑐𝑛𝑡[𝐴[𝑖]]]←𝐴[𝑖]12𝑐𝑛𝑡[𝐴[𝑖]]←𝑐𝑛𝑡[𝐴[𝑖]]−113𝐫𝐞𝐭𝐮𝐫𝐧 𝐵![\begin{array}{ll}
1 & \textbf{Input. } \text{An array } A \text{ consisting of }n\text{ positive integers no greater than } w. \\
2 & \textbf{Output. } \text{Array }A\text{ after sorting in nondecreasing order stably.} \\
3 & \textbf{Method. } \\
4 & \textbf{for }i\gets0\textbf{ to }w\\
5 & \qquad \textit{cnt}[i]\gets0\\
6 & \textbf{for }i\gets1\textbf{ to }n\\
7 & \qquad \textit{cnt}[A[i]]\gets\textit{cnt}[A[i]]+1\\
8 & \textbf{for }i\gets1\textbf{ to }w\\
9 & \qquad \textit{cnt}[i]\gets \textit{cnt}[i]+\textit{cnt}[i-1]\\
10 & \textbf{for }i\gets n\textbf{ downto }1\\
11 & \qquad B[\textit{cnt}[A[i]]]\gets A[i]\\
12 & \qquad \textit{cnt}[A[i]]\gets \textit{cnt}[A[i]]-1\\
13 & \textbf{return } B
\end{array}](data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7)
参考资料与注释
本页面最近更新:2025/9/21 16:51:30,更新历史
发现错误?想一起完善? 在 GitHub 上编辑此页!
本页面贡献者:NachtgeistW, iamtwz, Tiphereth-A, Enter-tainer, Junyan721113, ksyx, Xeonacid, Alisahhh, c-forrest, gi-b716, Great-designer, Konano, mcendu, Menci, minghu6, ouuan, shawlleyw, sun2snow, TrickEye
本页面的全部内容在 CC BY-SA 4.0 和 SATA 协议之条款下提供,附加条款亦可能应用