From 332f6dfbebcc1272e638b65bcf6bc487630e13de Mon Sep 17 00:00:00 2001 From: Omar Boukli-Hacene Date: Thu, 8 Feb 2024 22:10:17 +0200 Subject: [PATCH] refactor: Revisit quicksort --- include/forfun/sorting/quicksort.hpp | 31 +++++++++++++++------------- 1 file changed, 17 insertions(+), 14 deletions(-) diff --git a/include/forfun/sorting/quicksort.hpp b/include/forfun/sorting/quicksort.hpp index c9f89e3..f349bfd 100644 --- a/include/forfun/sorting/quicksort.hpp +++ b/include/forfun/sorting/quicksort.hpp @@ -19,26 +19,29 @@ namespace { template requires std::contiguous_iterator -[[nodiscard]] constexpr inline auto +[[nodiscard]] constexpr inline Iter partition(Iter const first, Iter const last) noexcept { - auto const pivot_itr{first}; - auto const pivot{*pivot_itr}; - auto i{first}; - for (auto j{last - 1}; j != i;) + { - if (*j < pivot) - { - std::iter_swap(++i, j); - } - else + using DiffType = std::iter_difference_t; + + auto const pivot{*first}; + for (auto j{last - DiffType{1}}; j != i;) { - --j; + if (*j < pivot) + { + std::iter_swap(++i, j); + } + else + { + --j; + } } } - std::iter_swap(pivot_itr, i); + std::iter_swap(first, i); return i; } @@ -55,10 +58,10 @@ constexpr inline void quicksort(Iter const first, Iter const last) noexcept { return; } - + auto const p{partition(first, last)}; quicksort(first, p); - quicksort(p + 1, last); + quicksort(p + DiffType{1}, last); } } // namespace forfun::sorting