额外数组 C 中每一项的数值即是该 key 值下重复元素的个数,而该项的前缀和即是排在最后一个的重复元素的排名.
如果按照 A 的逆序进行排列,那么显然排序后的数组将保持 A 的原序(相同 key 值情况下),也即得到一种稳定的排序算法.
counting sort animate example
性质
稳定性
计数排序是一种稳定的排序算法.
时间复杂度
计数排序的时间复杂度为 O(n+w),其中 w 代表待排序数据的值域大小.
代码实现
伪代码
12345678910111213Input. An array A consisting of n positive integers no greater than w.Output. Array A after sorting in nondecreasing order stably.Method. for i←0 to wcnt[i]←0for i←1 to ncnt[A[i]]←cnt[A[i]]+1for i←1 to wcnt[i]←cnt[i]+cnt[i−1]for i←n downto 1B[cnt[A[i]]]←A[i]cnt[A[i]]←cnt[A[i]]−1return B
C++
#include<cstring>constexprint MAXN = 1010;
constexprint MAXW = 100010;
int cnt[MAXW], b[MAXN];
int* counting_sort(int* a, int n, int w){
memset(cnt, 0, sizeof(cnt));
for (int i = 1; i <= n; ++i) ++cnt[a[i]];
for (int i = 1; i <= w; ++i) cnt[i] += cnt[i - 1];
for (int i = n; i >= 1; --i) b[cnt[a[i]]--] = a[i];
return b;
}
Python
defcounting_sort(a, n, w):
b = [0] * n
cnt = [0] * (w + 1)
for i inrange(1, n + 1):
cnt[a[i]] += 1for i inrange(1, w + 1):
cnt[i] += cnt[i - 1]
for i inrange(n, 0, -1):
b[cnt[a[i]] - 1] = a[i]
cnt[a[i]] -= 1return b