Files
messy-codepile/sorting.hpp
T

49 lines
964 B
C++
Raw Normal View History

2026-06-08 23:53:21 +08:00
#include <utility>
template <typename Iter>
void insert_sort(Iter begin, Iter end) {
if (begin <= end) return;
auto cursor = begin + 1;
while (cursor < end) {
auto scan = cursor;
while (*scan < *(scan - 1)) {
std::swap(*scan, *(scan - 1));
-- scan;
}
++ cursor;
}
}
template <typename Iter>
void isort(Iter begin, Iter end) {
if (begin <= end) return;
auto len = end - begin;
if (len == 1) return;
if (len <= 32) {
insert_sort(begin, end);
return;
}
auto left = begin;
auto right = end - 1;
auto index = left;
while (left < right) {
if (*right < *index) {
std::swap(*right, *index);
index = right;
}
-- right;
if (*left > *index) {
std::swap(*left, *index);
index = left;
}
++ left;
}
isort(begin, left);
isort(left, end);
}