BAN: Cleanup intro_sort and quick_sort

Only recurse to the smaller partition. This prevents worst case O(n)
recursion
This commit is contained in:
2026-07-07 04:43:06 +03:00
parent 896bb05073
commit 7b4b5a3440

View File

@@ -67,11 +67,20 @@ namespace BAN::sort
template<typename It, typename Comp = less<it_value_type_t<It>>> template<typename It, typename Comp = less<it_value_type_t<It>>>
void quick_sort(It begin, It end, Comp comp = {}) void quick_sort(It begin, It end, Comp comp = {})
{ {
if (distance(begin, end) <= 1) while (distance(begin, end) > 1)
return; {
const auto [lt, gt] = detail::partition(begin, end, comp); const auto [lt, gt] = detail::partition(begin, end, comp);
quick_sort(begin, lt, comp); if (distance(begin, lt) < distance(gt, end))
quick_sort(gt, end, comp); {
quick_sort(begin, lt);
begin = gt;
}
else
{
quick_sort(gt, end);
end = lt;
}
}
} }
template<typename It, typename Comp = less<it_value_type_t<It>>> template<typename It, typename Comp = less<it_value_type_t<It>>>
@@ -102,13 +111,28 @@ namespace BAN::sort
template<typename It, typename Comp> template<typename It, typename Comp>
void intro_sort_impl(It begin, It end, size_t max_depth, Comp comp) void intro_sort_impl(It begin, It end, size_t max_depth, Comp comp)
{ {
if (distance(begin, end) <= 16) for (size_t i = 0; i < max_depth; i++)
return insertion_sort(begin, end, comp); {
if (max_depth == 0) const size_t len = distance(begin, end);
return heap_sort(begin, end, comp); if (len <= 1)
const auto [lt, gt] = detail::partition(begin, end, comp); return;
intro_sort_impl(begin, lt, max_depth - 1, comp); if (len <= 16)
intro_sort_impl(gt, end, max_depth - 1, comp); return insertion_sort(begin, end, comp);
const auto [lt, gt] = detail::partition(begin, end, comp);
if (distance(begin, lt) < distance(gt, end))
{
intro_sort_impl(begin, lt, max_depth - 1, comp);
begin = gt;
}
else
{
intro_sort_impl(gt, end, max_depth - 1, comp);
end = lt;
}
}
heap_sort(begin, end, comp);
} }
} }