For pure practice purposes, I started implementing different sorting algorithms in modern C++ in a standard library style way (i.e. using templates on iterators). This is my version of bubble sort.
I do not really have any specific criteria I would like to have the code reviewed under, but instead appreciate any hints I can get, be they on performance, coding style, expressiveness etc.
The whole implementation lives inside the file bubble_sort.h:
#pragma once
#include <utility>
template<typename Iterator, typename Comparator>
void bubble_sort(Iterator begin, Iterator end, Comparator cmp) {
bool swapped;
do {
swapped = false;
for (auto i = begin + 1; i != end; ++i) {
auto& val0 = *i;
auto& val1 = *(i - 1);
if (cmp(val0, val1)) {
std::swap(val1, val0);
swapped = true;
}
}
} while (swapped);
}
template<typename Iterator>
void bubble_sort(Iterator begin, Iterator end) {
bubble_sort(begin, end, [] (const typename Iterator::value_type& v0,
const typename Iterator::value_type& v1) { return v0 < v1; });
}
For reference, I also provide to you a file containing a main
-method which sorts a small std::vector
of random unsigned
s in ascending as well as descending order:
#include <random>
#include <vector>
#include <iostream>
#include "bubble_sort.h"
int main() {
std::vector<unsigned> vec;
std::default_random_engine engine;
std::uniform_int_distribution<unsigned> distribution(0, 10000);
for (std::size_t i = 0; i < 100; ++i) {
unsigned num = distribution(engine);
std::cout << num << ' ';
vec.push_back(num);
}
std::cout << "\n\n";
bubble_sort(vec.begin(), vec.end());
for (unsigned e : vec) {
std::cout << e << ' ';
}
std::cout << "\n\n";
bubble_sort(vec.begin(), vec.end(), [] (unsigned v0, unsigned v1) {
return v0 > v1;
});
for (unsigned e : vec) {
std::cout << e << ' ';
}
std::cout << '\n';
}