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; });