std::sort

Header: <algorithm>

Sorts the elements in [first, last) into non-descending order.

std::sort is not stable: equivalent elements may be reordered. Use std::stable_sort when preserving relative order of equal elements matters.

# Declarations

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

(constexpr since C++20)

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

(since C++17)

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

(constexpr since C++20)

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

(since C++17)

# Example

#include <algorithm>
#include <array>
#include <functional>
#include <iostream>

int main()
{
    std::array<int, 8> v{5, 1, 8, 3, 3, 7, 2, 4};

    std::sort(v.begin(), v.end());
    for (int x : v)
        std::cout << x << ' ';
    std::cout << '\n';

    std::sort(v.begin(), v.end(), std::greater<int>{});
    for (int x : v)
        std::cout << x << ' ';
    std::cout << '\n';
}

# Semantics

# Parameters

# Complexity

OverloadsComparator applications
(1), (3)O(N log N) comparisons (worst case)
(2), (4)O(N log N) comparator applications

Where N = std::distance(first, last).

# Exceptions

For overloads taking an execution policy:

# Notes

Typical implementations use introsort to satisfy worst-case O(N log N) while preserving good average performance.

# See also

# Defect reports

DRApplied toBehavior as publishedCorrect behavior
LWG 713C++98O(N log N) was only required on averagerequired in the worst case