Skip to content

Commit

Permalink
refactor: Revisit quicksort
Browse files Browse the repository at this point in the history
  • Loading branch information
oboukli committed Feb 8, 2024
1 parent 88882f5 commit 332f6df
Showing 1 changed file with 17 additions and 14 deletions.
31 changes: 17 additions & 14 deletions include/forfun/sorting/quicksort.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -19,26 +19,29 @@ namespace {

template <typename Iter>
requires std::contiguous_iterator<Iter>
[[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<Iter>;

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;
}
Expand All @@ -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
Expand Down

0 comments on commit 332f6df

Please sign in to comment.