計數排序和基數排序
計數排序不比較:數出每個值有幾個,再按順序寫回,k 種值時是 O(n + k);基數排序按個位、十位、百位逐位排,每一位用一次穩定的計數排序。
可以證明:只靠「比較兩個數誰大」來排序,最壞情況至少要比 log₂(n!) ≈ n log₂ n 次。歸併和快排已經到了這個下限,std::sort 也一樣。想更快,就得不比較:如果知道這些數都是 0 到 99 的整數(成績、年齡、埠號),直接數一數每個值有幾個就行了。
計數排序:數一數,再寫回去
開一個 vector<int> cnt(k, 0)(k 是值的範圍,k 個格子都是 0):先掃一遍,每個值的計數加一;再從小到大,每個值寫回它出現的次數。
i1#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] 是什麼?
哪一組資料最適合用計數排序?
寫計數排序
✓值都在 0~9 之間。補全計數和寫回兩步。
0 2 2 5 7 7 7 9
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}
出現最多的成績
✓成績都在 0~100 之間。用計數陣列找出出現次數最多的成績(一樣多時取小的),印出成績和次數。
88 3
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}
基數排序:一位一位排
數的範圍很大時,可以按位來:先按個位排、再按十位、再按百位……每一位只有 0~9 十種,用計數排序(這裡要「穩定」的版本)。排完最高位,整個陣列就有序了。
| 原來 | 按個位排 | 按十位排 | 按百位排 |
|---|---|---|---|
| 170 | 170 | 802 | 2 |
| 45 | 90 | 2 | 24 |
| 75 | 802 | 24 | 45 |
| 90 | 2 | 45 | 66 |
| 802 | 24 | 66 | 75 |
| 24 | 45 | 170 | 90 |
| 2 | 75 | 75 | 170 |
| 66 | 66 | 90 | 802 |
為什麼按個位排完、再按十位排,個位的順序不會被打亂?因為每一趟都是穩定的:十位相同的數(比如 802 和 2,十位都是 0),保持上一趟(按個位)排好的先後。所以最後一趟排完,高位相同的數,低位也已經是有序的了。
d 位數、每位 10 種:O(d × (n + 10))。適合位數固定的整數、等長的字串(按字元一位位排)。小數、要按自定義規則比較的物件,就只能用比較排序。
按個位(穩定地)排一趟,31 12 22 41 13 變成什麼?
100 萬個 6 位數的學號,用每位 10 種的基數排序,大約要做多少步?
每一趟怎麼排:穩定的計數排序
穩定的計數排序不再是「數完直接寫回值」,而是把每一條搬到它該去的位置:先對 cnt 做字首和,cnt[d] 就成了「鍵 ≤ d 的有幾個」,也就是鍵為 d 的那一組最後一個該放的位置再加一;然後從後往前掃,每條放到 --cnt[鍵]。
i基數排序的每一趟就是這樣一次計數排序,鍵是「這一位的數字」x / exp % 10:
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}
cnt[d] 是「值 ≤ d 的有幾個」:1 2 3 5。所以兩個 3 要放在下標 3 和 4,從後往前放時,後面那個 3 先放進下標 cnt[3] − 1 = 4。每一趟要從後往前把數放進 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}
n 開始會讀到陣列外面;從 0 開始的話,迴圈只跑一次。這些數最多三位。只改綠框裡的數,讓程式顯示完全排好的 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,它是歸併排序,和計數排序一樣穩定。
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 再 second | O(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;