Skip to content

Instantly share code, notes, and snippets.

@JIghtuse
Last active April 4, 2022 09:14
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JIghtuse/3772fce79376e2c35c4f480eb892610e to your computer and use it in GitHub Desktop.
Save JIghtuse/3772fce79376e2c35c4f480eb892610e to your computer and use it in GitHub Desktop.
Some sort algorithms in modern C++
#pragma once
#include <algorithm>
#include <functional>
template<typename ForwardIt, typename Compare = std::less<>>
void insertion_sort(ForwardIt begin, ForwardIt end, Compare comp = Compare{})
{
if (std::distance(begin, end) < 2) {
return;
}
for (auto it = begin; it != end; ++it) {
const auto first_larger_it = std::upper_bound(begin, it, *it, comp);
std::rotate(first_larger_it, it, it + 1);
}
}
template<typename Container, typename Compare = std::less<>>
void insertion_sort(Container& c, Compare comp = Compare{})
{
insertion_sort(std::begin(c), std::end(c), comp);
}
#pragma once
#include <algorithm>
#include <functional>
template<class ForwardIt, class Compare = std::less<>>
void merge_sort(ForwardIt begin, ForwardIt end, Compare cmp = Compare{})
{
auto const N = std::distance(begin, end);
if (N <= 1) return;
auto const middle = std::next(begin, N / 2);
merge_sort(begin, middle, cmp);
merge_sort(middle, end, cmp);
std::inplace_merge(begin, middle, end, cmp);
}
template<typename Container, typename Compare = std::less<>>
void merge_sort(Container& c, Compare comp = Compare{})
{
merge_sort(std::begin(c), std::end(c), comp);
}
#pragma once
#include <algorithm>
#include <functional>
template<typename ForwardIt, typename Compare = std::less<>>
void selection_sort(ForwardIt begin, ForwardIt end, Compare comp = Compare{})
{
if (std::distance(begin, end) < 2) {
return;
}
for (auto it = begin; it != end; ++it) {
const auto min = std::min_element(it, end);
std::iter_swap(min, it);
}
}
template<typename Container, typename Compare = std::less<>>
void selection_sort(Container& c, Compare comp = Compare{})
{
selection_sort(std::begin(c), std::end(c), comp);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment