题型与套路:排序
这一课复习排序:八种排序的时间、空间、稳定性放在一张表里,讲怎么给 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}