std::partial_sort

Header: <algorithm>

Rearranges elements such that the range [first,middle) contains the sorted middle − first smallest elements in the range [first,last).

# Declarations

template< class RandomIt >
void partial_sort( RandomIt first, RandomIt middle, RandomIt last );

(constexpr since C++20)

template< class ExecutionPolicy, class RandomIt >
void partial_sort( ExecutionPolicy&& policy,
RandomIt first, RandomIt middle, RandomIt last );

(since C++17)

template< class RandomIt, class Compare >
void partial_sort( RandomIt first, RandomIt middle, RandomIt last,
Compare comp );

(constexpr since C++20)

template< class ExecutionPolicy, class RandomIt, class Compare >
void partial_sort( ExecutionPolicy&& policy,
RandomIt first, RandomIt middle, RandomIt last,
Compare comp );

(since C++17)

# Parameters

# Notes

The algorithm used is typically heap select to select the smallest elements, and heap sort to sort the selected elements in the heap in ascending order.

To select elements, a heap is used (see heap). For example, for operator< as comparison function, max-heap is used to select middle − first smallest elements.

Heap sort is used after selection to sort [first,middle) selected elements (see std::sort_heap).

std::partial_sort algorithms are intended to be used for small constant numbers of [first,middle) selected elements.

# Example

#include <algorithm>
#include <array>
#include <functional>
#include <iostream>
 
void print(const auto& s, int middle)
{
    for (int a : s)
        std::cout << a << ' ';
    std::cout << '\n';
    if (middle > 0)
    {
        while (middle-- > 0)
            std::cout << "--";
        std::cout << '^';
    }
    else if (middle < 0)
    {
        for (auto i = s.size() + middle; --i; std::cout << "  ")
        {}
 
        for (std::cout << '^'; middle++ < 0; std::cout << "--")
        {}
    }
    std::cout << '\n';
};
 
int main()
{
    std::array<int, 10> s{5, 7, 4, 2, 8, 6, 1, 9, 0, 3};
    print(s, 0);
    std::partial_sort(s.begin(), s.begin() + 3, s.end());
    print(s, 3);
    std::partial_sort(s.rbegin(), s.rbegin() + 4, s.rend());
    print(s, -4);
    std::partial_sort(s.rbegin(), s.rbegin() + 5, s.rend(), std::greater{});
    print(s, -5);
}

# Defect reports

DRApplied toBehavior as publishedCorrect behavior
P0896R4C++98[first, middle) and [middle, last)were not required to be valid rangesthe behavior is undefinedif any of them is invalid

# See also