Sort a vector with bubble sort

Description: Sort {64, 34, 25, 12, 22, 11, 90} without std::sort, then check the result with std::sort.

Hint:

  • Swap neighbours which are in the wrong order. Repeat.

Solution

#include <algorithm>
#include <iostream>
#include <vector>

void bubble_sort(std::vector<int>& a) {
    for (std::size_t i = 0; i + 1 < a.size(); i++) {
        bool swapped = false;
        for (std::size_t j = 0; j + 1 < a.size() - i; j++) {
            if (a[j] > a[j + 1]) {
                std::swap(a[j], a[j + 1]);
                swapped = true;
            }
        }
        if (!swapped) break;
    }
}

int main() {
    std::vector<int> data = {64, 34, 25, 12, 22, 11, 90};
    auto check = data;
    bubble_sort(data);
    std::sort(check.begin(), check.end());
    for (int x : data) std::cout << x << ' ';
    std::cout << '\n' << (data == check) << '\n';
}
Output

11 12 22 25 34 64 90
1

How it works

  • After every round of the outer loop, the biggest remaining item is in its place.
  • It is slow (O(n squared)). Real code uses std::sort.

Read C++ Vectors.


Learn more about the similar topics:
Tutorials
No Content Found.
Exercises & Assignments
No Content Found.
Interview Questions & Answers
No Content Found.