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++"
const int N = 100010;const int W = 100010;int n, w, a[N], cnt[W], b[N];void counting_sort() { 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];}
"Python"
N = W = 100010n = w = 0a = b = [0] * Ncnt = [0] * Wdef counting_sort(): for i in range(1, n + 1): cnt[a[i]] += 1 for i in range(1, w + 1): cnt[i] += cnt[i - 1] for i in range(n, 0, -1): b[cnt[a[i]] - 1] = a[i] cnt[a[i]] -= 1