From 6caa9b6f95504c546f4ae10dfae6ed14a11fb2ad Mon Sep 17 00:00:00 2001 From: Bananymous Date: Thu, 7 Dec 2023 11:17:05 +0200 Subject: [PATCH] BAN: implement quick sort and test for it --- BAN/include/BAN/Sort.h | 37 ++++++++++++++++++++++++++++++++++++ userspace/test-sort/main.cpp | 4 ++++ 2 files changed, 41 insertions(+) diff --git a/BAN/include/BAN/Sort.h b/BAN/include/BAN/Sort.h index 4f1f6ab25d..e30e5fb50f 100644 --- a/BAN/include/BAN/Sort.h +++ b/BAN/include/BAN/Sort.h @@ -15,6 +15,43 @@ namespace BAN swap(*lhs, *rhs); } + namespace detail + { + template + It sort_quick_partition(It begin, It end, Comp comp) + { + It pivot = end; --pivot; + + It it1 = begin; + for (It it2 = begin; it2 != pivot; ++it2) + { + if (comp(*it2, *pivot)) + { + swap(*it1, *it2); + ++it1; + } + } + + swap(*it1, *pivot); + + return it1; + } + + } + + template> + void sort_quick(It begin, It end, Comp comp = {}) + { + { + It it = begin; + if (it == end || ++it == end) + return; + } + + It mid = detail::sort_quick_partition(begin, end, comp); + sort_quick(begin, mid, comp); + sort_quick(++mid, end, comp); + } } diff --git a/userspace/test-sort/main.cpp b/userspace/test-sort/main.cpp index 0955f9942f..28d55faf18 100644 --- a/userspace/test-sort/main.cpp +++ b/userspace/test-sort/main.cpp @@ -34,4 +34,8 @@ int main() TEST("exchange sort", BAN::sort_exchange, 100); TEST("exchange sort", BAN::sort_exchange, 1000); TEST("exchange sort", BAN::sort_exchange, 10000); + + TEST("quick sort", BAN::sort_quick, 100); + TEST("quick sort", BAN::sort_quick, 1000); + TEST("quick sort", BAN::sort_quick, 10000); }