Kodewick
开始学 →
冒泡排序和选择排序41 / 52

冒泡排序和选择排序

第 41 课,共 52 课 · 第 8 部分 · 排序 · 约 15 分钟

冒泡排序相邻两个比、大的往后换,选择排序每轮把最小的放到前面;两者都是 O(n²),只有冒泡稳定,实际用 std::sort,要稳定就用 stable_sort。

给 n 个数排序,最直接的想法是:每一轮让一个数到它该在的位置,n − 1 轮就排好了。冒泡排序和选择排序都是这么做的,区别在于这一轮怎么把那个数找出来、怎么挪过去。实际写代码时你会直接调 std::sort,但先亲手写一遍这两种,才知道「比较」「交换」「稳定」这些词指的是什么,也才看得出 sort 快在哪里。

冒泡排序:相邻的比,大的往后换

从头开始,相邻的两个比一比,前面的大就交换。走完一轮,最大的那个就像气泡一样「冒」到了最后。下一轮不用再管最后一个。

a比较 0 · 交换 05149201234
1for (int i = 0; i < n - 1; i++)2    for (int j = 0; j < n - 1 - i; j++)3        if (a[j] > a[j + 1])4            swap(a[j], a[j + 1]);

冒泡排序的第一轮:一路比到最后,最大的 9 换到了末尾

交换用的是 <utility> 里的 std::swap(x, y):它的参数是引用,直接换掉两个元素本身,不用像 C 那样传地址。排序函数也收一个 vector<int>&,改的就是调用者手里那个 vector。完整的程序在这里,它会自己一步步播放,数组画成柱子,交换的两个会滑过去:

main.cpp
1#include <iostream>2#include <vector>3#include <utility>4using namespace std;5 6void bubble_sort(vector<int>& a) {7    int n = a.size();8    for (int i = 0; i < n - 1; i++)9        for (int j = 0; j < n - 1 - i; j++)10            if (a[j] > a[j + 1])11                swap(a[j], a[j + 1]);12}13 14int main() {15    vector<int> a = {5, 1, 4, 9, 2};16    bubble_sort(a);17    for (int x : a)18        cout << x << " ";19    cout << "\n";20    return 0;21}
输出
1 2 4 5 9 
单选

对 3 6 2 5 1 做冒泡排序(从小到大),走完第 1 趟数组是什么样?

填空点一个填进空格,再点空格可以拿回来

冒泡排序交换的是相邻的两个。在空格里填上数字,让程序把 3 6 2 5 1 排好。

1#include <iostream>2#include <vector>3#include <utility>4using namespace std;5 6int main() {7    vector<int> a = {3, 6, 2, 5, 1};8    int n = a.size();9    for (int i = 0; i < n - 1; i++)10        for (int j = 0; j < n - 1 - i; j++)11            if (a[j] > a[j + 1])12                swap(a[j], a[j + ]);13    for (int x : a)14        cout << x << " ";15    cout << "\n";16    return 0;17}

已经有序就提前停

如果某一轮一次都没换,说明已经排好了,后面的轮次都可以省掉。加一个 bool swapped 标记:

1for (int i = 0; i < n - 1; i++) {2    bool swapped = false;3    for (int j = 0; j < n - 1 - i; j++)4        if (a[j] > a[j + 1]) {5            swap(a[j], a[j + 1]);6            swapped = true;7        }8    if (!swapped) break;    // 这一轮没换:已经有序9}

这样对一个已经有序的数组,只走一轮、比 n − 1 次就结束:最好情况是 O(n)。

猜输出猜错也没关系

1 2 3 5 4 只差一对没排好。加了提前结束以后,一共走了几轮?

1#include <iostream>2#include <vector>3#include <utility>4using namespace std;5 6int main() {7    vector<int> a = {1, 2, 3, 5, 4};8    int n = a.size(), rounds = 0;9    for (int i = 0; i < n - 1; i++) {10        bool swapped = false;11        rounds++;12        for (int j = 0; j < n - 1 - i; j++)13            if (a[j] > a[j + 1]) {14                swap(a[j], a[j + 1]);15                swapped = true;16            }17        if (!swapped) break;18    }19    cout << rounds << "\n";20    return 0;21}
单选

带提前结束的冒泡排序,碰到哪种输入最慢?

练习 1

写冒泡排序(带提前结束)

补全 bubble_sort:相邻的比、前面的大就交换;某一轮没换就提前结束。函数返回一共交换了几次。

要显示
1 2 3 6 7 8
7
exercise1.cpp
1#include <iostream>2#include <vector>3#include <utility>4using namespace std;5 6int bubble_sort(vector<int>& a) {7    int n = a.size(), swaps = 0;8    // 相邻的比,前面的大就 swap(swaps++);某一轮没换就 break9    return swaps;10}11 12int main() {13    vector<int> a = {3, 7, 1, 8, 2, 6};14    int swaps = bubble_sort(a);15    for (int x : a)16        cout << x << " ";17    cout << "\n" << swaps << "\n";18    return 0;19}
输出
点「运行」或按 Ctrl+Enter

选择排序:每一轮挑最小的

选择排序换个思路:第 i 轮在 a[i] 到最后里找出最小的,和 a[i] 交换。每一轮只换一次。

a比较 0 · 交换 05149201234
1for (int i = 0; i < n - 1; i++) {2    int m = i;3    for (int j = i + 1; j < n; j++)4        if (a[j] < a[m]) m = j;5    swap(a[i], a[m]);6}

选择排序的第一轮:m 记着目前最小的下标,走完一遍再把它换到最前面

下标变量叫 m 而不叫 min:using namespace std; 以后,min 是 std::min 的名字,自己再用容易混。

main.cpp
1#include <iostream>2#include <vector>3#include <utility>4using namespace std;5 6void selection_sort(vector<int>& a) {7    int n = a.size();8    for (int i = 0; i < n - 1; i++) {9        int m = i;10        for (int j = i + 1; j < n; j++)11            if (a[j] < a[m])12                m = j;13        swap(a[i], a[m]);14    }15}16 17int main() {18    vector<int> a = {5, 1, 4, 9, 2};19    selection_sort(a);20    for (int x : a)21        cout << x << " ";22    cout << "\n";23    return 0;24}
输出
1 2 4 5 9 
单选

对 5 1 4 9 2 做选择排序,走完第 2 趟数组是什么样?

填空点一个填进空格,再点空格可以拿回来

找到更小的数时要记下什么?在空格里填上,让选择排序把 5 1 4 9 2 排好。

1#include <iostream>2#include <vector>3#include <utility>4using namespace std;5 6int main() {7    vector<int> a = {5, 1, 4, 9, 2};8    int n = a.size();9    for (int i = 0; i < n - 1; i++) {10        int m = i;11        for (int j = i + 1; j < n; j++)12            if (a[j] < a[m])13                m = ;14        swap(a[i], a[m]);15    }16    for (int x : a)17        cout << x << " ";18    cout << "\n";19    return 0;20}
练习 2

从大到小的选择排序

改成从大到小:每一轮挑出最大的放到前面。

要显示
9 7 5 4 2
exercise2.cpp
1#include <iostream>2#include <vector>3#include <utility>4using namespace std;5 6void selection_sort_desc(vector<int>& a) {7    int n = a.size();8    for (int i = 0; i < n - 1; i++) {9        int m = i;10        // 在 a[i+1..n-1] 里找最大的下标,再和 a[i] 交换11    }12}13 14int main() {15    vector<int> a = {4, 9, 2, 7, 5};16    selection_sort_desc(a);17    for (int x : a)18        cout << x << " ";19    cout << "\n";20    return 0;21}
输出
点「运行」或按 Ctrl+Enter

比较和交换各几次

两种排序都是两层循环,比较次数一样:(n − 1) + (n − 2) + … + 1 = n(n − 1)/2,O(n²)。差别在交换:

比较交换(最坏)最好情况稳定吗
冒泡(带提前结束)n(n − 1)/2n(n − 1)/2O(n),已经有序稳定
选择n(n − 1)/2n − 1O(n²),怎么都要比完不稳定

稳定的意思是:两个相等的数,排完以后前后顺序不变。冒泡只换相邻的、而且相等时不换,所以稳定;选择排序会把一个数「跳着」换到很远的地方。这段程序给每个数带一个字母标签,用 pair<int, char> 存,只按数字比:

main.cpp
1#include <iostream>2#include <vector>3#include <utility>4using namespace std;5 6int main() {7    vector<pair<int, char>> a = {{2, 'a'}, {2, 'b'}, {1, 'c'}};8    int n = a.size();9    for (int i = 0; i < n - 1; i++) {        // 选择排序,只比 first10        int m = i;11        for (int j = i + 1; j < n; j++)12            if (a[j].first < a[m].first)13                m = j;14        swap(a[i], a[m]);15    }16    for (auto& p : a)17        cout << p.first << p.second << " ";18    cout << "\n";19    return 0;20}
输出
1c 2b 2a 

第一轮把 1c 和 2a 交换,2a 一下跳到了最后,变成 1c 2b 2a:两个 2 的顺序反了。按多个条件排序(先按成绩、再按学号)时,稳定很重要。

考试里: 「每一轮能确定一个元素的最终位置」的排序:冒泡(确定最大的)、选择(确定最小的)、堆排序;「交换次数最少」:选择排序,最多 n − 1 次。

单选

5a 8 5b 2 里有两个 5(a、b 只是用来区分它们)。选择排序走完第 1 趟后是什么样?

改一改

每个人有分数和名字,按分数从小到大冒泡排序。现在的写法分数相同也会交换。只改绿框里的比较符号,让分数相同的人保持原来的先后(A 在 C 前面,B 在 D 前面)。

1#include <iostream>2#include <vector>3#include <utility>4using namespace std;5 6struct Item {7    int score;8    char name;9};10 11int main() {12    vector<Item> a = {{2, 'A'}, {1, 'B'}, {2, 'C'}, {1, 'D'}};13    int n = a.size();14    for (int i = 0; i < n - 1; i++)15        for (int j = 0; j < n - 1 - i; j++)16            if (a[j].score  a[j + 1].score)17                swap(a[j], a[j + 1]);18    for (auto& p : a)19        cout << p.score << p.name << " ";20    cout << "\n";21    return 0;22}
要显示
1B 1D 2A 2C

用 STL 写

平时不会自己写冒泡:<algorithm> 里的 sort(first, last) 排好 [first, last) 这一段,默认从小到大。第三个参数是比较函数 comp(x, y):x 应该排在 y 前面就返回 true。可以传 greater<int>()(<functional>),也可以当场写一个 lambda。要稳定,就用 stable_sort,参数一样。

main.cpp
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, 1, 4, 9, 2};15    sort(a.begin(), a.end());                       // 从小到大16    for (int x : a) cout << x << " ";17    cout << "\n";18 19    sort(a.begin(), a.end(), greater<int>());       // 从大到小20    for (int x : a) cout << x << " ";21    cout << "\n";22 23    vector<int> b = {15, 22, 7, 30, 41};24    sort(b.begin(), b.end(), [](int x, int y) {     // 按个位数从小到大25        return x % 10 < y % 10;26    });27    for (int x : b) cout << x << " ";28    cout << "\n";29 30    vector<Student> s = {{"Ann", 85}, {"Bob", 92}, {"Cat", 85}, {"Dan", 92}};31    stable_sort(s.begin(), s.end(), [](const Student& x, const Student& y) {32        return x.score > y.score;                   // 按分数从高到低33    });34    for (auto& t : s) cout << t.name << " " << t.score << "\n";35    return 0;36}
输出
1 2 4 5 9 
9 5 4 2 1 
30 41 22 15 7 
Bob 92
Dan 92
Ann 85
Cat 85

stable_sort 保证同分的两个人保持原来的先后:Bob 在 Dan 前面,Ann 在 Cat 前面。sort 不保证这一点,同分的谁先谁后都有可能。

sort 里面是内省排序(introsort):平时用快速排序,递归太深就改用堆排序,切到很小的段再用插入排序,所以最坏也是 O(n log n)。它比冒泡快多少?用一个会计数的 lambda 数一数,同样是 500 个倒序的数:

main.cpp
1#include <iostream>2#include <vector>3#include <utility>4#include <algorithm>5using namespace std;6 7int main() {8    int n = 500;9    vector<int> a(n), b(n);10    for (int i = 0; i < n; i++) a[i] = b[i] = n - i;    // 500 499 … 111 12    long long c1 = 0;                                  // 冒泡的比较次数13    for (int i = 0; i < n - 1; i++)14        for (int j = 0; j < n - 1 - i; j++) {15            c1++;16            if (a[j] > a[j + 1]) swap(a[j], a[j + 1]);17        }18 19    long long c2 = 0;                                  // sort 调了几次比较函数20    sort(b.begin(), b.end(), [&c2](int x, int y) {21        c2++;22        return x < y;23    });24 25    cout << "冒泡:" << c1 << " 次比较\n";26    cout << "sort:" << c2 << " 次比较\n";27    cout << (a == b ? "结果一样" : "结果不同") << "\n";28    return 0;29}
输出
冒泡:124750 次比较
sort:3574 次比较
结果一样

冒泡比了 n(n − 1)/2 = 124750 次;sort 只调了几千次比较函数,差了几十倍,n 越大差得越多(n² 对 n log n)。lambda 写成 [&c2] 是按引用捕获:里面的 c2++ 改的是外面那个变量。

写法做什么时间稳定
swap(x, y)换两个变量(引用传参)O(1)
sort(b, e)从小到大O(n log n),introsort不保证
sort(b, e, greater<int>())从大到小O(n log n)不保证
sort(b, e, [](…){ … })按自己的规则O(n log n)不保证
stable_sort(b, e, comp)相等的保持原顺序O(n log n),归并排序稳定
min_element(b, e)找最小的(选择排序的一轮)O(n)

比较函数一定要写严格的 < 或 >,不能写 <=:两个相等的数,comp(x, x) 必须返回 false。写成 <= 时 sort 可能越界读到数组外面去,程序直接崩溃。

面试里: 「冒泡和选择哪个稳定」「std::sort 是什么排序、稳定吗」(introsort,不稳定;要稳定用 stable_sort)是常见的问法。按多个条件排序时,比较函数里先比第一个条件,相等再比第二个;或者先按次要条件排,再按主要条件 stable_sort 一遍。

猜输出猜错也没关系

比较函数比的是个位数,而且是 >。排完是什么顺序?

1#include <iostream>2#include <vector>3#include <algorithm>4using namespace std;5 6int main() {7    vector<int> a = {15, 22, 7, 30, 41};8    sort(a.begin(), a.end(), [](int x, int y) {9        return x % 10 > y % 10;10    });11    for (int x : a)12        cout << x << " ";13    cout << "\n";14    return 0;15}
单选

一组学生要按分数从高到低排,同分的保持原来的先后。哪一种写对了?

小结

这一课带走

冒泡和选择:每一轮定下一个数,都是 O(n²)

  • 冒泡:相邻的比,大的往后换;一轮没换就提前结束,最好 O(n);稳定
  • 选择:每一轮找最小的下标,只换一次,最多 n − 1 次交换;不稳定
  • 平时用 sort(introsort,O(n log n),不稳定),要稳定用 stable_sort
  • 比较函数:x 该在 y 前面就返回 true,只能写严格的 < 或 >
1for (int i = 0; i < n - 1; i++)2    for (int j = 0; j < n - 1 - i; j++)3        if (a[j] > a[j + 1]) swap(a[j], a[j + 1]);4sort(a.begin(), a.end(), greater<int>());5stable_sort(s.begin(), s.end(), [](const Student& x, const Student& y) { return x.score > y.score; });