題型與套路:排序
這一課複習排序:八種排序的時間、空間、穩定性放在一張表裡,講怎麼給 std::sort 寫比較(lambda、greater<int>()、多個鍵),以及三個套路:排序後掃一遍、自定順序、只要前 k 個。
前面五課寫了八種排序,可工作裡幾乎不會自己寫排序:std::sort 是 introsort,最壞 O(n log n),比手寫的快排還快。考試裡排序題通常考比較:哪種穩定、哪種最壞也是 O(n log n)、一趟之後陣列長什麼樣。面試裡的排序題,大部分落在三個套路上:排好以後從左往右掃一遍;按自己定的規則排;只要前 k 個、不要全部排好。
一張表比完所有排序
| 排序 | 平均 | 最壞 | 最好 | 額外空間 | 穩定 | 一趟後能定下 |
|---|---|---|---|---|---|---|
| 冒泡 | O(n²) | O(n²) | O(n) | O(1) | 穩定 | 最大的一個 |
| 選擇 | O(n²) | O(n²) | O(n²) | O(1) | 不穩定 | 最小的一個 |
| 插入 | O(n²) | O(n²) | O(n) | O(1) | 穩定 | 不能 |
| 希爾 | 約 O(n^1.3) | O(n²) | O(1) | 不穩定 | 不能 | |
| 歸併 | O(n log n) | O(n log n) | O(n log n) | O(n) | 穩定 | 不能 |
| 快速 | O(n log n) | O(n²) | O(n log n) | O(log n) | 不穩定 | 基準一個 |
| 計數 | O(n + k) | O(n + k) | O(n + k) | O(k) | 穩定 | |
| 基數 | O(d(n + r)) | O(d(n + r)) | O(n + r) | 穩定 |
記法:不穩定的四個是「選、希、快、堆」(堆排序在前面「樹」那一章講過,也不穩定)。
怎麼選:
- 資料量小(幾十個)或幾乎有序:插入排序。
std::sort最後一遍用的就是它。 - 要穩定、或者是鏈結串列:歸併排序(STL 裡是
stable_sort和list::sort)。 - 一般情況:
std::sort,快排加堆排序兜底,最壞也 O(n log n)。 - 整數、範圍不大:計數排序;位數固定:基數排序。
哪些排序是不穩定的?(可以選好幾個)
套路一:先排序,再掃一遍
很多題亂著很難,排好以後從左往右掃一遍就解決了:相等的挨在一起(找重複、去重),重疊的區間挨在一起(合併區間、會議室),兩數之和也可以從兩頭往中間夾。排序 O(n log n),掃一遍 O(n)。
合併區間:按起點排好,每個區間只要和 out 裡最後一個比:起點不超過它的終點,就重疊,合併成一個;否則另起一個。
i區間用 pair<int, int> 存,sort 排 pair 先比 first,正好就是按起點排;out.back() 是 out 裡最後一個,可以直接改。
1#include <iostream>2#include <vector>3#include <algorithm>4#include <utility>5using namespace std;6 7int main() {8 vector<pair<int, int>> v = {{8, 10}, {1, 3}, {15, 18}, {2, 6}, {9, 12}};9 sort(v.begin(), v.end()); // 按起點排10 vector<pair<int, int>> out;11 for (const pair<int, int>& x : v) {12 if (!out.empty() && x.first <= out.back().second)13 out.back().second = max(out.back().second, x.second); // 重疊:合併14 else15 out.push_back(x); // 不重疊:另起一個16 }17 for (const pair<int, int>& x : out)18 cout << "[" << x.first << ", " << x.second << "] ";19 cout << "\n";20 return 0;21}
[1, 6] [8, 12] [15, 18]
不排序的話,每個區間都要和其他所有的比,O(n²);排好以後重疊的一定挨著,一遍就夠。
區間已經按起點排好:1-4 3-5 6-8 8-9 11-12。照這一關的規則(起點不超過 out 裡最後一個的終點就合併)合併完是什麼?
數組裡有沒有重複
✓先用 sort 排好,有重複的話一定挨在一起:只要比較相鄰的。印出 1(有)或 0(沒有)。
0 1
1#include <iostream>2#include <vector>3#include <algorithm>4using namespace std;5 6bool has_dup(vector<int> a) {7 // sort 排好,再看相鄰的有沒有相等8 return false;9}10 11int main() {12 vector<int> a = {8, 3, 5, 1, 9}, b = {4, 7, 2, 7, 1};13 cout << has_dup(a) << " " << has_dup(b) << "\n";14 return 0;15}
套路二:自己定順序
sort 的第三個引數是比較:一個函式,cmp(x, y) 返回 true 表示 x 應該排在 y 前面。最常用的三種寫法:
- 什麼都不給:用
<,從小到大; greater<int>()(在<functional>裡):用>,從大到小;- 一個 lambda:
[](const Student& x, const Student& y) { … },想怎麼比就怎麼比。
按多個鍵排:分數從高到低,分數一樣的按名字從 A 到 Z。比較裡先比分數,分數不同就由分數定;一樣才比名字。
| 名字 | 分數 | 由什麼定的 |
|---|---|---|
| Dan | 95 | 分數 |
| Amy | 90 | 名字 |
| Cat | 90 | 名字 |
| Bob | 85 | 分數 |
1#include <iostream>2#include <vector>3#include <string>4#include <algorithm>5#include <functional>6using namespace std;7 8struct Student {9 string name;10 int score;11};12 13int main() {14 vector<int> a = {5, 2, 8, 1, 9, 3};15 sort(a.begin(), a.end(), greater<int>());16 for (int x : a) cout << x << " ";17 cout << "\n";18 19 vector<Student> s = {{"Cat", 90}, {"Bob", 85}, {"Dan", 95}, {"Amy", 90}};20 sort(s.begin(), s.end(), [](const Student& x, const Student& y) {21 if (x.score != y.score) return x.score > y.score; // 分數高的在前22 return x.name < y.name; // 一樣高:名字小的在前23 });24 for (const Student& t : s)25 cout << t.name << " " << t.score << "\n";26 return 0;27}
9 8 5 3 2 1 Dan 95 Amy 90 Cat 90 Bob 85
另一個辦法是利用穩定:先按名字排,再用 stable_sort 按分數排,分數一樣的保持上一遍排好的名字順序。也可以在 struct 裡寫 bool operator<(const Student& o) const,以後 sort(s.begin(), s.end()) 就預設用它。
兩個坑。一是比較必須是嚴格的:x.score >= y.score 這種寫法,兩個一樣的數會「互相都排在前面」,std::sort 的結果是未定義的,資料多時甚至會越界。二是 sort 不穩定:只按分數比的話,Amy 和 Cat 誰先誰後說不準;要確定的順序,就把名字也寫進比較,或者用 stable_sort。C 裡 qsort 的比較要返回負數、0、正數,return x - y 還會溢位;C++ 的比較只返回 bool,沒有這個問題。
分數從高到低,分數一樣的按名字從 A 到 Z。填上兩個比較符號,讓程式顯示 Dan Amy Cat Bob。
1#include <iostream>2#include <vector>3#include <string>4#include <algorithm>5using namespace std;6 7struct Student {8 string name;9 int score;10};11 12int main() {13 vector<Student> s = {{"Bob", 85}, {"Amy", 90}, {"Dan", 95}, {"Cat", 90}};14 sort(s.begin(), s.end(), [](const Student& x, const Student& y) {15 if (x.score != y.score) return x.score y.score;16 return x.name y.name;17 });18 for (const Student& t : s)19 cout << t.name << " ";20 cout << "\n";21 return 0;22}
cmp(x, y) 返回 true 表示 x 排在 y 前面。分數高的在前,所以是 x.score > y.score;名字小的在前,是 x.name < y.name。不要寫 >= 或 <=:比較必須是嚴格的,兩個一樣的不能「互相都排在前面」。按兩個條件排序
✓補全 lambda:年齡小的在前,年齡一樣時編號小的在前。
5 1 2 3 4
1#include <iostream>2#include <vector>3#include <algorithm>4using namespace std;5 6struct P {7 int id;8 int age;9};10 11int main() {12 vector<P> p = {{3, 30}, {1, 25}, {4, 30}, {2, 25}, {5, 18}};13 sort(p.begin(), p.end(), [](const P& x, const P& y) {14 // 先比 age,一樣再比 id15 return false;16 });17 for (const P& t : p)18 cout << t.id << " ";19 cout << "\n";20 return 0;21}
套路三:只要前 k 個
找第 k 小的數,全部排序是 O(n log n)。快速選擇借用快排的劃分:劃分一次以後,基準在下標 m。如果 m 正好是 k,就找到了;k 在左邊就只去左邊找,在右邊就只去右邊。每次只走一邊,平均 O(n)。
1#include <iostream>2#include <vector>3#include <utility>4using namespace std;5 6int partition(vector<int>& a, int lo, int hi) {7 int p = a[hi], i = lo;8 for (int j = lo; j < hi; j++)9 if (a[j] < p) swap(a[i++], a[j]);10 swap(a[i], a[hi]);11 return i;12}13 14// 第 k 小(k 從 0 數)15int select_k(vector<int>& a, int k) {16 int lo = 0, hi = a.size() - 1;17 while (true) {18 int m = partition(a, lo, hi);19 if (m == k) return a[m];20 if (k < m) hi = m - 1;21 else lo = m + 1;22 }23}24 25int main() {26 vector<int> a = {7, 2, 9, 4, 3, 8, 5};27 cout << "第 3 小:" << select_k(a, 2) << "\n";28 for (int x : a) cout << x << " ";29 cout << "\n";30 return 0;31}
第 3 小:4 2 3 4 5 9 8 7
打印出來的陣列是 2 3 4 5 9 8 7:第 3 小的 4 在下標 2,左邊都比它小,右邊都比它大,但右邊並沒有排好。「中位數」「第 k 大」「前 k 小」都是這個套路;另一個常見答案是一個大小為 k 的堆,O(n log k),資料一條條流過來時也能用。
快速選擇
✓partition 已經給你了。補全 select_k:劃分後基準在 m,等於 k 就返回,否則只去一邊接著找。
3 7
1#include <iostream>2#include <vector>3#include <utility>4using namespace std;5 6int partition(vector<int>& a, int lo, int hi) {7 int p = a[hi], i = lo;8 for (int j = lo; j < hi; j++)9 if (a[j] < p) swap(a[i++], a[j]);10 swap(a[i], a[hi]);11 return i;12}13 14int select_k(vector<int> a, int k) {15 int lo = 0, hi = a.size() - 1;16 // 迴圈:m = partition;m == k 返回 a[m];k < m 去左邊,否則去右邊17 return -1;18}19 20int main() {21 vector<int> a = {12, 3, 5, 7, 4, 19, 26};22 cout << select_k(a, 0) << " " << select_k(a, 3) << "\n";23 return 0;24}
用 STL 寫
三個套路在 STL 裡都有現成的:
1#include <iostream>2#include <vector>3#include <queue>4#include <algorithm>5#include <functional>6using namespace std;7 8int main() {9 vector<int> a = {58, 91, 72, 66, 99, 43, 87, 95, 60, 77};10 int k = 3;11 12 // 前 k 大,排好:只排前 k 個13 vector<int> b = a;14 partial_sort(b.begin(), b.begin() + k, b.end(), greater<int>());15 cout << "partial_sort:";16 for (int i = 0; i < k; i++) cout << b[i] << " ";17 cout << "\n";18 19 // 第 k 大:nth_element 就是快速選擇20 vector<int> c = a;21 nth_element(c.begin(), c.begin() + (k - 1), c.end(), greater<int>());22 cout << "第 " << k << " 大:" << c[k - 1] << "\n";23 24 // 前 k 大,資料一個個來:大小為 k 的小頂堆,多了就踢掉最小的25 priority_queue<int, vector<int>, greater<int>> q;26 for (int x : a) {27 q.push(x);28 if ((int)q.size() > k) q.pop();29 }30 cout << "堆裡:";31 while (!q.empty()) { cout << q.top() << " "; q.pop(); }32 cout << "\n";33 34 // 排好以後去重:相等的挨在一起35 vector<int> d = {3, 1, 3, 2, 1, 3};36 sort(d.begin(), d.end());37 d.erase(unique(d.begin(), d.end()), d.end());38 cout << "去重:";39 for (int x : d) cout << x << " ";40 cout << "\n";41 return 0;42}
partial_sort:99 95 91 第 3 大:91 堆裡:91 95 99 去重:1 2 3
partial_sort 裡是堆:前 k 個建成堆,後面的比堆頂好就換進來,最後把這 k 個排好。priority_queue 用 greater<int> 才是小頂堆(預設是大頂堆),彈出來是從小到大。unique 只把相鄰的重複挪到後面、返回新的末尾,所以要先排序,再 erase 掉後面那段。
| 要做的 | 寫法 | 代價 |
|---|---|---|
| 全部排好 | sort(b, e, cmp) | O(n log n),不穩定 |
| 排好且一樣的保持先後 | stable_sort(b, e, cmp) | O(n log n),O(n) 額外空間 |
| 前 k 個排好 | partial_sort(b, b + k, e, cmp) | O(n log k) |
| 只要第 k 個 | nth_element(b, b + k, e, cmp) | 平均 O(n) |
| 資料流裡的前 k 大 | 大小為 k 的 priority_queue<int, vector<int>, greater<int>> | O(n log k),O(k) 記憶體 |
| 去重 | sort + unique + erase | O(n log n) |
面試裡: 先說「排個序就簡單了」的題:合併區間、會議室、兩數之和(雙指標)、找重複,複雜度 O(n log n)。按多個鍵排,lambda 裡先比主鍵、不同就返回,一樣再比次鍵。第 k 大先答堆 O(n log k),再答 nth_element 平均 O(n)。被問「比較函式能不能寫 <=」:不能,必須是嚴格弱序,否則 std::sort 是未定義行為。
沒有先排序就直接 unique。程式輸出幾?
1#include <iostream>2#include <vector>3#include <algorithm>4using namespace std;5 6int main() {7 vector<int> a = {1, 3, 3, 1, 1, 2};8 a.erase(unique(a.begin(), a.end()), a.end());9 cout << a.size() << "\n";10 return 0;11}
unique 只把相鄰的重複去掉:1 3 3 1 1 2 變成 1 3 1 2,剩 4 個。兩個 1 不挨著,留下了兩次。要真正去重,先 sort 成 1 1 1 2 3 3,再 unique + erase,才剩 1 2 3 三個。小結
排序三個套路
- 不穩定的四個:選、希、快、堆;最壞也 O(n log n):歸併、堆(還有 std::sort)
- 先排序再掃一遍:合併區間、找重複、去重(sort + unique)
- 自己定順序:lambda 先比主鍵再比次鍵,必須是嚴格的;greater<int>() 從大到小;要穩定用 stable_sort
- 只要前 k 個:快速選擇 / nth_element 平均 O(n);partial_sort 和大小為 k 的堆 O(n log k)
1sort(s.begin(), s.end(), [](const Student& x, const Student& y) {2 if (x.score != y.score) return x.score > y.score;3 return x.name < y.name;4});5nth_element(a.begin(), a.begin() + k, a.end());
第 7 章快刷
5 道題:冒泡和選擇的一輪、希爾的一趟、快排的比較次數、歸併的呼叫次數、基數排序的一趟。先自己算出印出什麼,再點選項。
氣泡排序和選擇排序都對 4 3 2 1 只走一輪,印出什麼?
1#include <iostream>2#include <vector>3#include <utility>4using namespace std;5 6int main() {7 vector<int> a = {4, 3, 2, 1}, b = {4, 3, 2, 1};8 for (int j = 0; j < 3; j++) // 冒泡一輪9 if (a[j] > a[j + 1]) swap(a[j], a[j + 1]);10 int m = 0; // 選擇一輪11 for (int j = 1; j < 4; j++)12 if (b[j] < b[m]) m = j;13 swap(b[0], b[m]);14 for (int x : a) cout << x << " ";15 cout << "| ";16 for (int x : b) cout << x << " ";17 cout << "\n";18 return 0;19}
希爾排序間隔為 2 的那一趟,對 9 8 7 6 5 4 做完,印出什麼?
1#include <iostream>2#include <vector>3using namespace std;4 5int main() {6 vector<int> a = {9, 8, 7, 6, 5, 4};7 int n = a.size(), gap = 2;8 for (int i = gap; i < n; i++) {9 int key = a[i], j = i - gap;10 while (j >= 0 && a[j] > key) {11 a[j + gap] = a[j];12 j -= gap;13 }14 a[j + gap] = key;15 }16 for (int x : a) cout << x << " ";17 cout << "\n";18 return 0;19}
基準取最後一個的快速排序,排已經有序的 0 到 9,比較了幾次?
1#include <iostream>2#include <vector>3#include <utility>4using namespace std;5 6long long cmps = 0;7 8void qs(vector<int>& a, int lo, int hi) {9 if (lo >= hi) return;10 int p = a[hi], i = lo;11 for (int j = lo; j < hi; j++) {12 cmps++;13 if (a[j] < p) swap(a[i++], a[j]);14 }15 swap(a[i], a[hi]);16 qs(a, lo, i - 1);17 qs(a, i + 1, hi);18}19 20int main() {21 vector<int> a(10);22 for (int i = 0; i < 10; i++) a[i] = i;23 qs(a, 0, 9);24 cout << cmps << "\n";25 return 0;26}
歸併排序 6 個數,merge_sort 一共被呼叫幾次?
1#include <iostream>2using namespace std;3 4int calls = 0;5 6void ms(int lo, int hi) {7 calls++;8 if (lo >= hi) return;9 int mid = (lo + hi) / 2;10 ms(lo, mid);11 ms(mid + 1, hi);12}13 14int main() {15 ms(0, 5);16 cout << calls << "\n";17 return 0;18}
基數排序的第一趟:按個位做一次穩定的計數排序。印出什麼?
1#include <iostream>2#include <vector>3using namespace std;4 5int main() {6 vector<int> a = {21, 12, 31, 22};7 int n = a.size();8 vector<int> out(n), cnt(10, 0);9 for (int x : a) cnt[x % 10]++;10 for (int d = 1; d < 10; d++) cnt[d] += cnt[d - 1];11 for (int i = n - 1; i >= 0; i--)12 out[--cnt[a[i] % 10]] = a[i];13 for (int x : out) cout << x << " ";14 cout << "\n";15 return 0;16}