Kodewick
开始学 →
计数排序和基数排序45 / 52

计数排序和基数排序

第 45 课,共 52 课 · 第 8 部分 · 排序 · 约 22 分钟

计数排序不比较:数出每个值有几个,再按顺序写回,k 种值时是 O(n + k);基数排序按个位、十位、百位逐位排,每一位用一次稳定的计数排序。

可以证明:只靠「比较两个数谁大」来排序,最坏情况至少要比 log₂(n!) ≈ n log₂ n 次。归并和快排已经到了这个下限,std::sort 也一样。想更快,就得不比较:如果知道这些数都是 0 到 99 的整数(成绩、年龄、端口号),直接数一数每个值有几个就行了。

计数排序:数一数,再写回去

开一个 vector<int> cnt(k, 0)(k 是值的范围,k 个格子都是 0):先扫一遍,每个值的计数加一;再从小到大,每个值写回它出现的次数。

a(左 6 格)和 cnt[0..4](右 5 格)acnt[0..4]3141300000001234567891011↑i

给 3 1 4 1 3 0 计数:值是几,就在 cnt 的第几格加一;数完以后按 cnt 从小到大写回去
main.cpp
1#include <iostream>2#include <vector>3using namespace std;4 5int main() {6    vector<int> a = {3, 1, 4, 1, 3, 0};7    vector<int> cnt(5, 0);8    for (int x : a)9        cnt[x]++;10    int k = 0;11    for (int v = 0; v < 5; v++)12        while (cnt[v]-- > 0)13            a[k++] = v;14    for (int x : a)15        cout << x << " ";16    cout << "\n";17    return 0;18}
输出
0 1 1 3 3 4 

扫一遍是 n,再走一遍 cnt 是 k:O(n + k),额外空间 O(k)。100 万个 0~100 的成绩,它只要两百来万步,比快排的两千万次比较少得多。

但它有前提:值是整数,范围 k 不能太大。要是值在 0 到 10⁹ 之间,cnt 要 10⁹ 个 int,40 亿字节,根本开不出来。

猜输出猜错也没关系

数完以后打印 cnt[2] 和「有几个不同的值」,是什么?

1#include <iostream>2#include <vector>3using namespace std;4 5int main() {6    vector<int> a = {2, 5, 2, 8, 5, 2};7    vector<int> cnt(10, 0);8    for (int x : a)9        cnt[x]++;10    int distinct = 0;11    for (int v = 0; v < 10; v++)12        if (cnt[v] > 0) distinct++;13    cout << cnt[2] << " " << distinct << "\n";14    return 0;15}
单选

值都在 0~2 之间。对 2 0 2 1 0 2 计数以后,cnt[0] cnt[1] cnt[2] 是什么?

单选

哪一组数据最适合用计数排序?

练习 1

写计数排序

值都在 0~9 之间。补全计数和写回两步。

要显示
0 2 2 5 7 7 7 9
exercise1.cpp
1#include <iostream>2#include <vector>3using namespace std;4 5int main() {6    vector<int> a = {7, 2, 9, 2, 0, 7, 7, 5};7    vector<int> cnt(10, 0);8    // 1. 每个值的 cnt 加一  2. 从 0 到 9,每个值写回 cnt[v] 次9    for (int x : a)10        cout << x << " ";11    cout << "\n";12    return 0;13}
输出
点「运行」或按 Ctrl+Enter
练习 2

出现最多的成绩

成绩都在 0~100 之间。用计数数组找出出现次数最多的成绩(一样多时取小的),打印成绩和次数。

要显示
88 3
exercise2.cpp
1#include <iostream>2#include <vector>3using namespace std;4 5int main() {6    vector<int> s = {88, 92, 75, 88, 60, 92, 88, 75, 100, 92};7    vector<int> cnt(101, 0);8    int best = 0;9    // 计数,然后从 0 到 100 找 cnt 最大的10    cout << best << " " << cnt[best] << "\n";11    return 0;12}
输出
点「运行」或按 Ctrl+Enter

基数排序:一位一位排

数的范围很大时,可以按位来:先按个位排、再按十位、再按百位……每一位只有 0~9 十种,用计数排序(这里要「稳定」的版本)。排完最高位,整个数组就有序了。

个位0123456789

按个位排一趟:个位是几就放进几号桶,同一个桶里按原来的先后排队;最后从 0 号桶到 9 号桶依次取出
原来按个位排按十位排按百位排
1701708022
4590224
758022445
9024566
802246675
244517090
27575170
666690802

为什么按个位排完、再按十位排,个位的顺序不会被打乱?因为每一趟都是稳定的:十位相同的数(比如 802 和 2,十位都是 0),保持上一趟(按个位)排好的先后。所以最后一趟排完,高位相同的数,低位也已经是有序的了。

d 位数、每位 10 种:O(d × (n + 10))。适合位数固定的整数、等长的字符串(按字符一位位排)。小数、要按自定义规则比较的对象,就只能用比较排序。

单选

按个位(稳定地)排一趟,31 12 22 41 13 变成什么?

单选

100 万个 6 位数的学号,用每位 10 种的基数排序,大约要做多少步?

每一趟怎么排:稳定的计数排序

稳定的计数排序不再是「数完直接写回值」,而是把每一条搬到它该去的位置:先对 cnt 做前缀和,cnt[d] 就成了「键 ≤ d 的有几个」,也就是键为 d 的那一组最后一个该放的位置再加一;然后从后往前扫,每条放到 --cnt[键]。

a(左 5 格)和 out(右 5 格)aout3a1b2c1d3e0123456789↑i

键是数字、字母记原来的先后。cnt[1..3] = 2, 1, 2,前缀和以后是 2, 3, 5;从右往左,每条放进 out[--cnt[键]]

基数排序的每一趟就是这样一次计数排序,键是「这一位的数字」x / exp % 10:

main.cpp
1#include <iostream>2#include <vector>3#include <string>4using namespace std;5 6void by_digit(vector<int>& a, int exp) {7    int n = a.size();8    vector<int> out(n), cnt(10, 0);9    for (int x : a) cnt[x / exp % 10]++;10    for (int d = 1; d < 10; d++) cnt[d] += cnt[d - 1];      // cnt[d]:这一位 ≤ d 的有几个11    for (int i = n - 1; i >= 0; i--)                       // 从后往前放:保持稳定12        out[--cnt[a[i] / exp % 10]] = a[i];13    a = out;14}15 16int main() {17    vector<int> a = {170, 45, 75, 90, 802, 24, 2, 66};18    string names[] = {"按个位", "按十位", "按百位"};19    int exp = 1;20    for (int t = 0; t < 3; t++, exp *= 10) {21        by_digit(a, exp);22        cout << names[t] << ":";23        for (int x : a) cout << x << " ";24        cout << "\n";25    }26    return 0;27}
输出
按个位:170 90 802 2 24 45 75 66 
按十位:802 2 24 45 66 170 75 90 
按百位:2 24 45 66 75 90 170 802 

注意 by_digit 里的两处:前缀和让 cnt[d] 变成「这一位 ≤ d 的有几个」,正好是这一组最后一个该放的位置再加一;从后往前放,相同的数才保持原来的先后。从前往后放,就不稳定了,结果会错。最后 a = out; 把整个 vector 复制回去。

猜输出猜错也没关系

计数以后再做前缀和,打印的 cnt 是什么?

1#include <iostream>2#include <vector>3using namespace std;4 5int main() {6    vector<int> a = {3, 1, 3, 0, 2};7    vector<int> cnt(4, 0);8    for (int x : a)9        cnt[x]++;10    for (int d = 1; d < 4; d++)11        cnt[d] += cnt[d - 1];12    for (int c : cnt)13        cout << c << " ";14    cout << "\n";15    return 0;16}
填空点一个填进空格,再点空格可以拿回来

每一趟要从后往前把数放进 out,排序才稳定。补上循环的起点,让程序显示排好的结果。

1#include <iostream>2#include <vector>3using namespace std;4 5void by_digit(vector<int>& a, int exp) {6    int n = a.size();7    vector<int> out(n), cnt(10, 0);8    for (int x : a) cnt[x / exp % 10]++;9    for (int d = 1; d < 10; d++) cnt[d] += cnt[d - 1];10    for (int i = ; i >= 0; i--)11        out[--cnt[a[i] / exp % 10]] = a[i];12    a = out;13}14 15int main() {16    vector<int> a = {329, 457, 657, 839, 436, 720, 355};17    for (int exp = 1; exp <= 100; exp *= 10)18        by_digit(a, exp);19    for (int x : a)20        cout << x << " ";21    cout << "\n";22    return 0;23}
改一改

这些数最多三位。只改绿框里的数,让程序显示完全排好的 329 355 436 457 657 720 839。

1#include <iostream>2#include <vector>3using namespace std;4 5void by_digit(vector<int>& a, int exp) {6    int n = a.size();7    vector<int> out(n), cnt(10, 0);8    for (int x : a) cnt[x / exp % 10]++;9    for (int d = 1; d < 10; d++) cnt[d] += cnt[d - 1];10    for (int i = n - 1; i >= 0; i--)11        out[--cnt[a[i] / exp % 10]] = a[i];12    a = out;13}14 15int main() {16    vector<int> a = {329, 457, 657, 839, 436, 720, 355};17    for (int exp = 1; exp <= ; exp *= 10)18        by_digit(a, exp);19    for (int x : a)20        cout << x << " ";21    cout << "\n";22    return 0;23}
要显示
329 355 436 457 657 720 839

用 STL 写

STL 里没有现成的计数排序,sort 已经够快;但计数本身天天用。cnt 的大小要到运行时才知道时,vector<int> cnt(mx + 1, 0) 正合适;只想知道某一个值有几个,用 <algorithm> 的 count,它从头扫到尾,O(n)。值的范围很大、很稀疏时,换成 map<int, int> 或 unordered_map<int, int> 计数(第 6 章)。

排序时元素的「大小」由 < 决定:string 按字典序一个字符一个字符比(大写字母的编码比小写小,排在前面),pair 先比 first,一样再比 second。只想按其中一个键排、又要一样的保持原来的先后,用 stable_sort,它是归并排序,和计数排序一样稳定。

main.cpp
1#include <iostream>2#include <vector>3#include <string>4#include <algorithm>5#include <utility>6using namespace std;7 8int main() {9    vector<int> a = {3, 1, 4, 1, 3, 0};10    int mx = *max_element(a.begin(), a.end());11    vector<int> cnt(mx + 1, 0);                 // 大小运行时才知道12    for (int x : a) cnt[x]++;13    cout << "1 出现 " << cnt[1] << " 次,count 数出来也是 " << count(a.begin(), a.end(), 1) << " 次\n";14 15    vector<string> w = {"pear", "apple", "fig", "Banana", "app"};16    sort(w.begin(), w.end());                   // 字典序17    for (const string& s : w) cout << s << " ";18    cout << "\n";19 20    vector<pair<int, char>> p = {{3, 'e'}, {1, 'd'}, {2, 'c'}, {1, 'b'}, {3, 'a'}};21    vector<pair<int, char>> q = p;22    sort(p.begin(), p.end());                   // 先比 first,一样再比 second23    stable_sort(q.begin(), q.end(), [](const pair<int, char>& x, const pair<int, char>& y) {24        return x.first < y.first;               // 只比 first25    });26    for (const pair<int, char>& x : p) cout << x.first << x.second << " ";27    cout << "\n";28    for (const pair<int, char>& x : q) cout << x.first << x.second << " ";29    cout << "\n";30    return 0;31}
输出
1 出现 2 次,count 数出来也是 2 次
Banana app apple fig pear 
1b 1d 2c 3a 3e 
1d 1b 2c 3e 3a 

"app" 排在 "apple" 前面:前三个字符一样,短的那个先比完,就算小。sort 排 pair 时 1b 在 1d 前面,因为 second 也参与了比较;stable_sort 只比 first,1d 和 1b、3e 和 3a 都保持了原来的先后,和上面稳定的计数排序得到的顺序一样。

写法做什么代价
vector<int> cnt(k, 0) + cnt[x]++范围小的整数计数O(n + k),O(k) 空间
count(b, e, x)数一个值有几个每次 O(n),要数很多值时用 cnt
map<int, int> 计数范围大、稀疏每次 O(log n)
sort 排 vector<string>字典序O(n log n) 次比较,每次比较最多 O(长度)
sort 排 vector<pair>先 first 再 secondO(n log n)
stable_sort(b, e, cmp)一样大的保持先后O(n log n),O(n) 额外空间

面试里: 「有没有比 O(n log n) 更快的排序」:有,但不是比较排序。计数排序 O(n + k)、基数排序 O(d(n + b)),前提是键是范围小的整数或能拆成位。常见题:「颜色分类」(只有 0、1、2 三个值,LeetCode 75),一遍计数、一遍写回;「数组里的数在 0~n 之间,O(n) 排序」。在循环里对每个值调用 count 是 O(n²) 的常见错误,先开一个 cnt 数一遍。

猜输出猜错也没关系

sort 排 vector<string> 按字典序。排完以后前两个是什么?

1#include <iostream>2#include <vector>3#include <string>4#include <algorithm>5using namespace std;6 7int main() {8    vector<string> w = {"pear", "app", "Banana", "apple"};9    sort(w.begin(), w.end());10    cout << w[0] << " " << w[1] << "\n";11    return 0;12}

小结

这一课带走

不比较的排序:计数和基数

  • 计数:cnt[值]++,再按值从小到大写回;O(n + k),k 是值的范围,只能用于范围不大的整数
  • 稳定版:前缀和得出位置,从后往前放
  • 基数:从低位到高位,每位一次稳定的计数排序;O(d(n + 10))
  • STL:vector<int> cnt 或 map 计数,count 是 O(n);pair 先比 first 再比 second;要稳定用 stable_sort
1vector<int> cnt(K, 0);2for (int x : a) cnt[x]++;3int k = 0;4for (int v = 0; v < K; v++)5    while (cnt[v]-- > 0) a[k++] = v;