Skip to content

Instantly share code, notes, and snippets.

@Rhomboid
Last active August 29, 2015 14:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Rhomboid/d5cf27e2a26ad4ae269a to your computer and use it in GitHub Desktop.
Save Rhomboid/d5cf27e2a26ad4ae269a to your computer and use it in GitHub Desktop.
bubble sort with lambda
#include <vector>
#include <string>
#include <random>
#include <iterator>
#include <iostream>
#include <algorithm>
template<typename T, typename Eng>
std::vector<T> make_random_ints(size_t n, Eng eng, T min, T max)
{
std::uniform_int_distribution<T> dist(min, max);
std::vector<T> data;
for(size_t i = 0; i < n; i++)
data.push_back(dist(eng));
return data;
}
template<typename Iter, typename Pred>
void bubblesort(Iter begin, Iter end, Pred p)
{
for(auto i = begin; i < end - 1; i++) {
for(auto j = i + 1; j < end; j++) {
if(p(*i, *j) > 0) {
std::swap(*i, *j);
}
}
}
}
template<typename Container, typename Pred>
void do_trial(Container c, Pred p, const std::string &message)
{
bubblesort(begin(c), end(c), p);
std::cout << message << '\n';
for(auto x : c) {
std::cout << x << ' ';
}
std::cout << "\n\n";
}
int main()
{
std::mt19937 mt(std::random_device{}());
auto data = make_random_ints(25, mt, 0, 100);
do_trial(data, [](const auto &a, const auto &b) { return a - b; }, "Ascending: ");
do_trial(data, [](const auto &a, const auto &b) { return b - a; }, "Descending: ");
do_trial(data, [](const auto &a, const auto &b) { return (a % 2) - (b % 2); }, "Even then odd: ");
do_trial(data, [](const auto &a, const auto &b) { return (b % 2) - (a % 2); }, "Odd then even: ");
do_trial(data, [](const auto &a, const auto &b) { auto x = a % 2, y = b % 2; if(x == y) return x ? (b - a) : (a - b); else return x - y; }, "Even ascending then odd descending: ");
do_trial(data, [](const auto &a, const auto &b) { auto x = a % 2, y = b % 2; if(x == y) return x ? (a - b) : (b - a); else return y - x; }, "Odd ascending then even descending: ");
}
$ g++ -Wall -Wextra -pedantic -std=c++1y -O2 -g bubblesort_lambda.cpp && ./a.out
Ascending:
3 5 17 22 23 23 24 32 38 39 41 42 45 47 47 48 56 56 59 62 64 69 76 94 97
Descending:
97 94 76 69 64 62 59 56 56 48 47 47 45 42 41 39 38 32 24 23 23 22 17 5 3
Even then odd:
76 48 38 94 24 62 56 22 32 56 64 42 59 17 69 97 3 41 45 47 23 23 39 5 47
Odd then even:
23 97 17 23 5 47 59 69 3 41 45 47 39 56 24 22 62 38 76 94 32 56 48 64 42
Even ascending then odd descending:
22 24 32 38 42 48 56 56 62 64 76 94 97 69 59 47 47 45 41 39 23 23 17 5 3
Odd ascending then even descending:
3 5 17 23 23 39 41 45 47 47 59 69 97 94 76 64 62 56 56 48 42 38 32 24 22
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment