Last active
April 4, 2022 09:14
-
-
Save JIghtuse/3772fce79376e2c35c4f480eb892610e to your computer and use it in GitHub Desktop.
Some sort algorithms in modern C++
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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); | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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); | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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