バブルソートと選択ソート
バブルソートは隣どうしを交換して大きいほうを後ろへ送り、選択ソートは毎回いちばん小さいものを前に置く方法で、どちらも O(n²)、安定なのはバブルソートだけで、実際には std::sort、安定性が必要なら stable_sort を使います。
n 個の数を整列するいちばん素直な方法:1 回の走査で 1 つの数を正しい場所に置き、n − 1 回走査すれば整列が終わります。バブルソートも選択ソートもこうしますが、1 回の走査でその数をどう見つけ、どう運ぶかが違います。実際のコードでは std::sort を呼びますが、先にこの 2 つを手で書くことで「比較」「交換」「安定」が何を意味するかを学び、sort がどこで時間を節約しているかが見えます。
バブルソート:隣どうしを比べ、大きいほうを後ろへ
先頭から隣り合う 2 つを比べ、前のほうが大きければ交換します。1 回走査すると最大のものが末尾へ「泡のように浮かび上がり」、次の走査では最後の 1 つは触らなくてよくなります。
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]);
交換には <utility> の std::swap(x, y) を使います:参照を受け取って 2 つの要素そのものを入れ替えるので、C のようにアドレスを渡す必要はありません。整列の関数も vector<int>& を受け取るので、呼び出し側の vector が変わります。プログラム全体です。1 ステップずつ自動で再生され、配列は棒で描かれ、交換される 2 つはすれ違うように動きます:
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 回目のパスの後、配列はどうなっていますか?
バブルソートが交換するのは隣どうしの 2 つです。空欄に数を入れて、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}
整列済みなら早めに止める
1 回の走査で一度も交換がなければ、配列は整列済みで、残りの走査は省けます。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 回の比較の走査 1 回で済みます:最良の場合は O(n) です。
1 2 3 5 4 は順序が逆の組が 1 つだけです。早めに止める版で、走査は何回でしょう?
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}
早期終了つきのバブルソートがいちばん遅くなる入力はどれですか?
バブルソートを書く(早めに止める版)
✓bubble_sort を埋めましょう:隣どうしを比べ、前が大きければ交換し、交換のない走査のあとは早めに止めます。関数は交換した回数を返します。
1 2 3 6 7 8 7
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 // 隣どうしを比べ、前が大きければ交換(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}
選択ソート:毎回最小のものを選ぶ
選択ソートは別のやり方をします:i 回目の走査で a[i] から末尾までの最小のものを見つけ、a[i] と交換します。1 回の走査で交換は 1 回です。
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}
添字の名前を min ではなく m にしているのは、using namespace std; のあとでは min が std::min の名前で、使い回すと紛らわしいからです。
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}
m が覚えているのは今までの最小の数の添字なので j です。a[j] だと数そのものを覚えてしまい、それを添字に使うと範囲外になります。i では何も新しく覚えません。大きい順の選択ソート
✓大きい順に整列しましょう:毎回いちばん大きいものを選んで前に置きます。
9 7 5 4 2
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}
比較と交換は何回か
どちらも二重ループで、比較の回数は同じです:(n − 1) + (n − 2) + … + 1 = n(n − 1)/2、O(n²)。違うのは交換です:
| 比較 | 交換(最悪) | 最良の場合 | 安定か | |
|---|---|---|---|---|
| バブル(早めに止める) | n(n − 1)/2 | n(n − 1)/2 | O(n)、整列済み | 安定 |
| 選択 | n(n − 1)/2 | n − 1 | O(n²)、いつも全部比べる | 安定でない |
安定とは、等しい 2 つの値が整列後も順序を保つことです。バブルソートは隣どうししか交換せず、等しいものは交換しないので安定です。選択ソートは値を遠くまで交換することがあります。このプログラムでは各数に文字の札をつけて pair<int, char> に入れ、数だけで比べます:
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++) { // 選択ソート、first だけで比べる10 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
1 回目の走査で 1c と 2a が交換され、2a が末尾へ跳んで 1c 2b 2a になります:2 つの 2 の順序が逆になりました。安定性は複数のキーで整列するとき(点数で、次に番号で)に大事です。
試験では: 1 回の走査ごとに 1 つの要素の最終位置が決まるソート:バブル(最大)、選択(最小)、ヒープソート。交換が最も少ないのは選択ソートで、多くても n − 1 回。
5a 8 5b 2 には 5 が 2 つあります(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
>= だと点数が等しい 2 人も交換され、前にいた人が後ろに回ります。> にすれば等しいときは交換せず、バブルソートは安定になります。STL で書く
バブルソートを本当に書く人はいません:<algorithm> の sort(first, last) は範囲 [first, last) を整列し、デフォルトは小さい順です。3 つ目の引数は比較関数 comp(x, y) で、x が y より前に来るべきとき true を返します。greater<int>()(<functional> にある)を渡すか、その場でラムダ式を書きます。安定な整列には stable_sort を使い、引数は同じです。
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 は、同じ点数の 2 人が元の順序を保つことを保証します:Bob が Dan の前、Ann が Cat の前。sort はそれを約束しないので、等しいものはどちらの順にも出てきえます。
sort の中身はイントロソートです:ふだんはクイックソート、再帰が深くなりすぎたらヒープソート、断片が小さくなったら挿入ソートなので、最悪でも O(n log n) です。バブルソートよりどれだけ速いでしょう? 同じ 500 個の逆順の数で、数を数えるラムダ式を使って数えてみます:
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)。ラムダ式の [&c2] は参照で取り込むので、中の c2++ が外の変数を変えます。
| 呼び出し | すること | 時間 | 安定 |
|---|---|---|---|
swap(x, y) | 2 つの変数を入れ替える(参照で) | O(1) | |
sort(b, e) | 小さい順 | O(n log n)、イントロソート | 保証なし |
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) | 最小を見つける(選択ソートの 1 回の走査) | O(n) |
比較関数は厳密、つまり < か > でなければならず、<= は決して使いません:等しい 2 つの値で comp(x, x) は false を返さなければならないからです。<= だと sort が配列の末尾を越えて読むことがあり、プログラムが落ちます。
面接では: 「バブルソートと選択ソートのどちらが安定か」「std::sort は何のソートで、安定か」(イントロソート、安定でない。安定にするなら stable_sort)はよく出ます。複数のキーで整列するなら、比較関数で 1 つ目のキーを比べ、同じときだけ 2 つ目を比べます。または先に従のキーで整列してから、主のキーで stable_sort します。
比較関数は 1 の位を比べていて、しかも > です。並べ替えた結果はどうなるでしょう?
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}
comp(x, y) が true なら x が y より前に来ます。つまり 1 の位が大きいものが先です。1 の位は 5 2 7 0 1 なので、大きい順に 7(7)、15(5)、22(2)、41(1)、30(0) です。学生を点数の高い順に並べ、同点の人は元の順番を保ちたいとします。正しいのはどれでしょう?
stable_sort が必要で、sort はそれを約束しません。比較関数は厳密な > でなければなりません。>= だと comp(x, x) が true になって決まりに反し、結果は信用できず、sort は範囲外を読むことさえあります。< では低い順になります。まとめ
バブルと選択:1 回の走査で 1 つ決まる、どちらも O(n²)
- バブル:隣どうしを比べ、大きいほうを後ろへ交換。交換のない走査で止まり、最良 O(n)。安定
- 選択:毎回最小の添字を見つけて 1 回交換、交換は多くても n − 1 回。安定でない
- 実際には sort(イントロソート、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; });