Kodewick
Start learning →
Bubble sort and selection sort41 / 52

Bubble sort and selection sort

Lesson 41 of 52 · Part 8 · Sorting · about 15 minutes

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.

acomparisons 0 · swaps 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]);

Bubble sort's first pass: comparing all the way along, the largest, 9, is swapped to the end

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:

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}
Output
1 2 4 5 9 
Choose one

Bubble sort 3 6 2 5 1 (smallest first). What does the array look like after pass 1?

Fill inTap one to fill a blank; tap a blank to take it back

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).

Guess the outputA wrong guess is fine

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}
Choose one

Which input is slowest for bubble sort with the early stop?

Exercise 1

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.

It should print
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    // 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}
Output
Press Run or Ctrl+Enter

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.

acomparisons 0 · swaps 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}

Selection sort's first pass: m holds the index of the smallest so far, and only at the end is it swapped to the front

The index is called m, not min: after using namespace std;, min is the name of std::min, and reusing it invites confusion.

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}
Output
1 2 4 5 9 
Choose one

Selection sort 5 1 4 9 2. What does the array look like after pass 2?

Fill inTap one to fill a blank; tap a blank to take it back

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}
Exercise 2

Selection sort, largest first

Make it sort largest first: each pass picks the largest and puts it in front.

It should print
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        // 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}
Output
Press Run or Ctrl+Enter

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:

ComparisonsSwaps (worst)Best caseStable?
Bubble (with early stop)n(n − 1)/2n(n − 1)/2O(n), already sortedstable
Selectionn(n − 1)/2n − 1O(n²), it always compares everythingunstable

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:

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++) {        // 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}
Output
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.

Choose one

5a 8 5b 2 has two 5s (a and b only tell them apart). What does selection sort make of it after pass 1?

Change it

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}
Should print
1B 1D 2A 2C

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.

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());                       // 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}
Output
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:

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;                                  // 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}
Output
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.

CallWhat it doesTimeStable
swap(x, y)swaps two variables (by reference)O(1)
sort(b, e)smallest firstO(n log n), introsortnot guaranteed
sort(b, e, greater<int>())largest firstO(n log n)not guaranteed
sort(b, e, [](…){ … })by your own ruleO(n log n)not guaranteed
stable_sort(b, e, comp)equal ones keep their orderO(n log n), merge sortstable
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.

Guess the outputA wrong guess is fine

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}
Choose one

A list of students must be sorted by score from high to low, with equal scores keeping their original order. Which one is right?

Summary

Take-away

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