Bubble sort and selection sort
Bubble sort swaps neighbours to move the bigger one back, and selection sort puts the smallest in front each pass; both are O(n²), only bubble sort is stable, and in practice you use std::sort, or stable_sort for stability.
The most direct way to sort n numbers: each pass puts one number where it belongs, and n − 1 passes later it's sorted. Bubble sort and selection sort both do this; they differ in how a pass finds that number and how it gets it there. In real code you call std::sort, but writing these two by hand first is how you learn what "comparison", "swap" and "stable" mean, and how you see where sort saves its time.
Bubble sort: compare neighbours, swap the bigger back
From the start, compare each pair of neighbours and swap when the first is bigger. After one pass the largest has "bubbled" to the end, and the next pass can leave the last one alone.
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]);
The swap is std::swap(x, y) from <utility>: it takes references and swaps the two elements themselves, with no addresses to pass as in C. The sort function takes a vector<int>& too, so it changes the caller's vector. Here is the whole program. It plays itself step by step, the array drawn as bars, and the two being swapped slide past each other:
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
Bubble sort 3 6 2 5 1 (smallest first). What does the array look like after pass 1?
Bubble sort swaps two neighbours. Fill in the number so the program sorts 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}
Stop early when it's sorted
If a pass makes no swap at all, the array is sorted and the remaining passes can be skipped. Add a bool swapped flag:
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; // no swap this pass: sorted9}
On an already sorted array it then takes one pass of n − 1 comparisons: the best case is O(n).
1 2 3 5 4 has just one pair out of order. With the early stop, how many passes does it take?
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}
Which input is slowest for bubble sort with the early stop?
Write bubble sort (with the early stop)
✓Fill in bubble_sort: compare neighbours, swap when the first is bigger; stop early after a pass with no swap. The function returns how many swaps it made.
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 // compare neighbours, swap if the first is bigger (swaps++); break after a pass with no swap9 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}
Selection sort: pick the smallest each pass
Selection sort goes about it differently: pass i finds the smallest of a[i] to the end and swaps it with a[i]. One swap per pass.
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}
The index is called m, not min: after using namespace std;, min is the name of std::min, and reusing it invites confusion.
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
Selection sort 5 1 4 9 2. What does the array look like after pass 2?
What do you remember when you find a smaller number? Fill in the blank so selection sort sorts 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 holds the index of the smallest number so far, so it is j. a[j] would store the number itself, which then goes out of bounds when used as an index; i remembers nothing new.Selection sort, largest first
✓Make it sort largest first: each pass picks the largest and puts it in front.
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 // find the index of the largest in a[i+1..n-1], then swap it with 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}
How many comparisons and swaps
Both are two nested loops with the same comparisons: (n − 1) + (n − 2) + … + 1 = n(n − 1)/2, O(n²). They differ in swaps:
| Comparisons | Swaps (worst) | Best case | Stable? | |
|---|---|---|---|---|
| Bubble (with early stop) | n(n − 1)/2 | n(n − 1)/2 | O(n), already sorted | stable |
| Selection | n(n − 1)/2 | n − 1 | O(n²), it always compares everything | unstable |
Stable means two equal values keep their order after sorting. Bubble sort only swaps neighbours, never equal ones, so it's stable; selection sort can swap a value a long way. In this program each number carries a letter tag, stored as a pair<int, char> and compared by the number only:
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++) { // selection sort, comparing first only10 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
The first pass swaps 1c with 2a, and 2a jumps to the end, giving 1c 2b 2a: the two 2s are reversed. Stability matters when sorting by several keys (by score, then by ID).
In exams: sorts where each pass fixes one element's final place: bubble (the largest), selection (the smallest), heap sort; fewest swaps: selection sort, at most n − 1.
5a 8 5b 2 has two 5s (a and b only tell them apart). What does selection sort make of it after pass 1?
Each person has a score and a name, bubble-sorted by score from low to high. As written, it swaps people with the same score too. Change only the comparison in the green box so people with the same score keep their original order (A before C, B before 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
>= swaps two people even when their scores are equal, so the one in front ends up behind. With >, equal scores are never swapped, and bubble sort is stable.With the STL
Nobody writes bubble sort for real: sort(first, last) from <algorithm> sorts the range [first, last), smallest first by default. The third argument is a comparator comp(x, y): it returns true when x should come before y. Pass greater<int>() (from <functional>), or write a lambda on the spot. For a stable sort use stable_sort, with the same arguments.
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()); // smallest first16 for (int x : a) cout << x << " ";17 cout << "\n";18 19 sort(a.begin(), a.end(), greater<int>()); // largest first20 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) { // by the last digit25 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; // highest score first33 });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 guarantees that two people with the same score keep their old order: Bob before Dan, Ann before Cat. sort makes no such promise; equal ones can come out either way.
Inside sort is introsort: quicksort most of the time, heap sort when the recursion gets too deep, and insertion sort once the pieces are small, so even the worst case is O(n log n). How much faster than bubble sort is it? Count with a lambda that keeps a tally, on the same 500 numbers in reverse:
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; // bubble sort's comparisons13 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; // calls of sort's comparator20 sort(b.begin(), b.end(), [&c2](int x, int y) {21 c2++;22 return x < y;23 });24 25 cout << "bubble: " << c1 << " comparisons\n";26 cout << "sort: " << c2 << " comparisons\n";27 cout << (a == b ? "same result" : "different results") << "\n";28 return 0;29}
bubble: 124750 comparisons sort: 3574 comparisons same result
Bubble sort compares n(n − 1)/2 = 124750 times; sort calls its comparator only a few thousand times, dozens of times fewer, and the gap grows with n (n² against n log n). The lambda's [&c2] captures by reference: the c2++ inside changes the variable outside.
| Call | What it does | Time | Stable |
|---|---|---|---|
swap(x, y) | swaps two variables (by reference) | O(1) | |
sort(b, e) | smallest first | O(n log n), introsort | not guaranteed |
sort(b, e, greater<int>()) | largest first | O(n log n) | not guaranteed |
sort(b, e, [](…){ … }) | by your own rule | O(n log n) | not guaranteed |
stable_sort(b, e, comp) | equal ones keep their order | O(n log n), merge sort | stable |
min_element(b, e) | finds the smallest (one pass of selection sort) | O(n) |
A comparator must be strict, < or >, never <=: for two equal values comp(x, x) has to return false. With <=, sort can read past the end of the array and the program crashes.
In interviews: "which of bubble and selection sort is stable" and "what sort is std::sort, is it stable" (introsort, not stable; use stable_sort for stability) come up often. To sort by several keys, compare the first key in the comparator and the second one only on a tie; or sort by the minor key first, then stable_sort by the major key.
The comparison looks at the last digit, and uses >. What order comes out?
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) returning true means x goes before y: the bigger last digit comes first. The last digits are 5 2 7 0 1; from big to small that's 7(7), 15(5), 22(2), 41(1), 30(0).A list of students must be sorted by score from high to low, with equal scores keeping their original order. Which one is right?
stable_sort; sort doesn't promise it. The comparison must be a strict >: with >=, comp(x, x) returns true, which breaks the rules, so the result can't be trusted and sort may even read out of bounds. < sorts from low to high.Summary
Bubble and selection: one number settled per pass, both O(n²)
- Bubble: compare neighbours, swap the bigger back; stop after a pass with no swap, best case O(n); stable
- Selection: find the smallest's index each pass, swap once, at most n − 1 swaps; not stable
- In practice use sort (introsort, O(n log n), not stable), or stable_sort for stability
- Comparator: true when x goes before y, strict < or > only
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; });