diff --git a/libs/core/algorithms/include/hpx/parallel/algorithms/partial_sort.hpp b/libs/core/algorithms/include/hpx/parallel/algorithms/partial_sort.hpp index cb79b8b7cd9..3b2f4e58b28 100644 --- a/libs/core/algorithms/include/hpx/parallel/algorithms/partial_sort.hpp +++ b/libs/core/algorithms/include/hpx/parallel/algorithms/partial_sort.hpp @@ -420,8 +420,15 @@ namespace hpx::parallel { HPX_MOVE(left), HPX_MOVE(right)); } + // The range was narrowed to [first, c_last). The caller expects + // the end of the whole range, as in the cases above, not the end + // of the part that was sorted. return parallel_partial_sort(HPX_FORWARD(ExPolicy, policy), first, - middle, c_last, level - 1, HPX_FORWARD(Comp, comp)); + middle, c_last, level - 1, HPX_FORWARD(Comp, comp)) + .then(hpx::launch::sync, [last](hpx::future&& f) -> Iter { + f.get(); + return last; + }); } /// \endcond NOINTERNAL } // end namespace detail diff --git a/libs/core/algorithms/tests/unit/algorithms/partial_sort.cpp b/libs/core/algorithms/tests/unit/algorithms/partial_sort.cpp index e7ad0385716..0656ca9969e 100644 --- a/libs/core/algorithms/tests/unit/algorithms/partial_sort.cpp +++ b/libs/core/algorithms/tests/unit/algorithms/partial_sort.cpp @@ -230,6 +230,43 @@ void test_partial_sort_edge_cases() } } +// Only ranges with a sorted part of at least 4096 elements are split further +// in parallel. The iterator returned must still be the end of the whole range. +void test_partial_sort_large_returns_last() +{ + using namespace hpx::execution; + using compare_t = std::less; + + for (std::size_t size : {10007u, 100000u}) + { + std::vector input(size); + std::iota(input.begin(), input.end(), std::uint64_t{0}); + std::shuffle(input.begin(), input.end(), gen); + + std::size_t const middle_index = size / 2; + + { + auto values = input; + auto result = hpx::partial_sort(par, values.begin(), + values.begin() + static_cast(middle_index), + values.end(), compare_t()); + HPX_TEST(result == values.end()); + for (std::uint64_t j = 0; j < middle_index; ++j) + HPX_TEST_EQ(values[j], j); + } + + { + auto values = input; + auto f = hpx::partial_sort(par(task), values.begin(), + values.begin() + static_cast(middle_index), + values.end(), compare_t()); + HPX_TEST(f.get() == values.end()); + for (std::uint64_t j = 0; j < middle_index; ++j) + HPX_TEST_EQ(values[j], j); + } + } +} + void test_partial_sort_sorted_prefix_with_smaller_tail() { using namespace hpx::execution; @@ -280,6 +317,7 @@ void partial_sort_test() test_partial_sort(); test_partial_sort(); test_partial_sort_edge_cases(); + test_partial_sort_large_returns_last(); test_partial_sort_sorted_prefix_with_smaller_tail(); }