Files
messy-codepile/include/sort/sort.hpp
T
2026-06-09 02:22:28 +08:00

52 lines
1.1 KiB
C++

#include <utility>
template <typename Iter>
void insert_sort(Iter first, Iter last) {
if (first >= last) return;
auto head = first + 1;
while (head < last) {
auto cursor = head;
while (cursor > first) {
if (*cursor < *(cursor - 1)) {
std::swap(*cursor, *(cursor - 1));
}
else {
break;
}
--cursor;
}
++head;
}
}
template <typename Iter>
void isort(Iter first, Iter last) {
if (first >= last) return;
auto length = std::distance(first, last);
if (length < 32) {
insert_sort(first, last);
return;
}
auto left = first;
auto right = last - 1;
auto index = first;
while (left < right) {
while (*right >= *index && left < right) --right;
if (left >= right) break;
std::swap(*index, *right);
index = right;
while (*left <= *index && left < right) ++left;
if (left >= right) break;
std::swap(*index, *left);
index = left;
}
isort(first, index);
isort(index + 1, last);
}