commit fcd674ace13050bf08348dcbe829f5fb11d81871 Author: 12hydrogen Date: Mon Jun 8 23:53:21 2026 +0800 Save old files diff --git a/main b/main new file mode 100755 index 0000000..223e8ea Binary files /dev/null and b/main differ diff --git a/main.c b/main.c new file mode 100644 index 0000000..3bccb6c --- /dev/null +++ b/main.c @@ -0,0 +1,7 @@ +#include + +int main() { + printf("Hello, world!\n"); + + return 0; +} diff --git a/main.cpp b/main.cpp new file mode 100644 index 0000000..ccf795a --- /dev/null +++ b/main.cpp @@ -0,0 +1,53 @@ +#include +#include + +#include +#include + +#include "sorting.hpp" + +template +void shuffling(Iter begin, Iter end) { + static std::random_device rd; + static std::mt19937 rng(rd()); + + for (auto cur = end - 1; cur > begin; -- cur) { + int index = std::uniform_int_distribution<>(0, cur - begin)(rng); + std::swap(*(begin + index), *cur); + } +} + +template +void displaying(Iter begin, Iter end, int wrap) { + const char* end_c = " \n"; + for (auto cur = begin; cur < end; ++ cur) { + std::cout << *cur << end_c[((cur - begin + 1) % wrap) == 0]; + } + std::cout << std::endl; +} + +int main(int argc, char *argv[]) { + int length = 128; + + if (argc > 1) { + sscanf(argv[1], "%d", &length); + } + + std::vector list(length); + for (int i = 0; i < length; ++ i) { + list.at(i) = i + 1; + } + + std::cout << "Raw: \n"; + displaying(list.begin(), list.end(), 16); + + shuffling(list.begin(), list.end()); + std::cout << "Shuffle: \n"; + displaying(list.begin(), list.end(), 16); + + isort(list.begin(), list.end()); + std::cout << "Sorted: \n"; + displaying(list.begin(), list.end(), 16); + + return 0; +} diff --git a/sorting.hpp b/sorting.hpp new file mode 100644 index 0000000..e0bb068 --- /dev/null +++ b/sorting.hpp @@ -0,0 +1,48 @@ +#include + +template +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 +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); +}