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 |
|---|
| C++ Strings: std::string and string_view |
| C++ Arrays and std::array |
| C++ Vectors (std::vector) |
| Exercises & Assignments |
|---|
| Reverse a string |
| Check if a string is a palindrome |
| Count the vowels in a string |
| Find the second largest number in a vector |
| Sort a vector with bubble sort |
| Transpose a matrix |
| Interview Questions & Answers |
|---|
| What is the difference between an array and a vector in C++? |
| What is the difference between std::string and a char array in C++? |