std::ranges::partial_sort - cppreference.com
Namespaces
Variants

std::ranges::partial_sort

From cppreference.com
 
 
Algorithm library
Constrained algorithms and algorithms on ranges (C++20)
Constrained algorithms, e.g. ranges::copy, ranges::sort, ...
Non-modifying sequence operations    
Batch operations
(C++17)
Search operations
Modifying sequence operations
Copy operations
(C++11)
(C++11)
Swap operations
Transformation operations
Generation operations
Removing operations
Order-changing operations
(until C++17)(C++11)
(C++20)(C++20)
Sampling operations
(C++17)

Sorting and related operations
Partitioning operations
(C++11)    

Sorting operations
Binary search operations
(on partitioned ranges)
Set operations (on sorted ranges)
Merge operations (on sorted ranges)
Heap operations
Minimum/maximum operations
(C++11)
(C++17)
Lexicographical comparison operations
Permutation operations


 
Constrained algorithms
All names in this menu belong to namespace std::ranges
Non-modifying sequence operations
Fold operations (Helper templates)
Modifying sequence operations
Partitioning operations
Sorting operations
Binary search operations (on sorted ranges)
       
       
Set operations (on sorted ranges)
Heap operations
Minimum/maximum operations
       
       
Permutation operations
Specialized <memory> algorithms
Return types
 
Defined in header <algorithm>
Call signature
template< std::random_access_iterator I, std::sentinel_for<I> S,
          class Comp = ranges::less, class Proj = std::identity >
    requires std::sortable<I, Comp, Proj>
constexpr I
    partial_sort( I first, I middle, S last, Comp comp = {}, Proj proj = {} );
(1) (since C++20)
template< ranges::random_access_range R,
          class Comp = ranges::less, class Proj = std::identity >
    requires std::sortable<ranges::iterator_t<R>, Comp, Proj>
constexpr ranges::borrowed_iterator_t<R>
    partial_sort( R&& r, ranges::iterator_t<R> middle,
                  Comp comp = {}, Proj proj = {} );
(2) (since C++20)
template< /*execution-policy*/ Ep,
          std::random_access_iterator I, std::sized_sentinel_for<I> S,
          class Comp = ranges::less, class Proj = std::identity >
    requires std::sortable<I, Comp, Proj>
I partial_sort( Ep&& policy, I first, I middle, S last,
                Comp comp = {}, Proj proj = {} );
(3) (since C++26)
template< /*execution-policy*/ Ep, /*sized-random-access-range*/ R,
          class Comp = ranges::less, class Proj = std::identity >
    requires std::sortable<ranges::iterator_t<R>, Comp, Proj>
ranges::borrowed_iterator_t<R>
    partial_sort( Ep&& policy, R&& r, ranges::iterator_t<R> middle,
                  Comp comp = {}, Proj proj = {} );
(4) (since C++26)

For the definition of /*execution-policy*/, see this page; for the definition of /*sized-random-access-range*/, see this page.

1) Places the first middle - first elements from the target range [firstlast) as sorted with respect to the comparator comp and projection proj into the range [firstmiddle). The rest of the elements are placed in the range [middlelast) in an unspecified order.
2) Same as (1), but uses ranges::begin(r) as first and ranges::end(r) as last.
3) Same as (1), but executed according to policy.
4) Same as (3), but uses ranges::begin(r) as first and ranges::begin(r) + ranges::distance(r) as last.

The function-like entities described on this page are algorithm function objects (informally known as niebloids), that is:

Parameters

first, last - the iterator-sentinel pair defining the target range
r - the target range
middle - the end of the range of sorted elements
comp - the comparator to be applied to the (projected) elements
proj - the projection to be applied to the elements
policy - the execution policy to use

Return value

The past-the-end iterator of the target range.

Complexity

Given

  • M as ranges::distance(first, middle),
  • N as ranges::distance(first, last):
1,2) Approximately N·log(M) applications of comp, and twice as many applications of proj.
3,4) 𝓞(N·log(M)) applications of comp, and twice as many applications of proj.

Exceptions

3,4) During the execution process:
  • If the temporary memory resources required for parallelization are not available, std::bad_alloc is thrown.
  • If an uncaught exception is thrown while accessing objects via an algorithm argument, the behavior is determined by the execution policy (for standard policies, std::terminate is invoked).

Possible implementation

struct partial_sort_fn
{
    template<std::random_access_iterator I, std::sentinel_for<I> S,
             class Comp = ranges::less, class Proj = std::identity>
        requires std::sortable<I, Comp, Proj>
    constexpr I operator()(I first, I middle, S last,
                           Comp comp = {}, Proj proj = {}) const
    {
        if (first == middle)
            return ranges::next(first, last);
        ranges::make_heap(first, middle, comp, proj);
        auto it{middle};
        for (; it != last; ++it)
        {
            if (std::invoke(comp, std::invoke(proj, *it), std::invoke(proj, *first)))
            {
                ranges::pop_heap(first, middle, comp, proj);
                ranges::iter_swap(middle - 1, it);
                ranges::push_heap(first, middle, comp, proj);
            }
        }
        ranges::sort_heap(first, middle, comp, proj);
        return it;
    }
    
    template<ranges::random_access_range R,
             class Comp = ranges::less, class Proj = std::identity>
        requires std::sortable<ranges::iterator_t<R>, Comp, Proj>
    constexpr ranges::borrowed_iterator_t<R>
        operator()(R&& r, ranges::iterator_t<R> middle,
                   Comp comp = {}, Proj proj = {}) const
    {
        return (*this)(ranges::begin(r), std::move(middle), ranges::end(r),
                       std::move(comp), std::move(proj));
    }
};

inline constexpr partial_sort_fn partial_sort{};

Example

#include <algorithm>
#include <functional>
#include <iostream>
#include <string>
#include <vector>

void print(const auto& v)
{
    for (const char e : v)
        std::cout << e << ' ';
    std::cout << '\n';
}

void underscore(int n)
{
    while (n-- > 0)
        std::cout << "^ ";
    std::cout << '\n';
}

int main()
{
    static_assert('A' < 'a');
    std::vector<char> v{'x', 'P', 'y', 'C', 'z', 'w', 'P', 'o'};
    print(v);
    const int m{3};
    std::ranges::partial_sort(v, v.begin() + m);
    print(v), underscore(m);
    
    static_assert('1' < 'a');
    std::string s{"3a1b41c5"};
    print(s);
    std::ranges::partial_sort(s.begin(), s.begin() + m, s.end(), std::greater{});
    print(s), underscore(m);
}

Output:

x P y C z w P o
C P P y z x w o
^ ^ ^
3 a 1 b 4 1 c 5
c b a 1 3 1 4 5
^ ^ ^

See also