algorithm_sort

algorithm_sort (정렬)

std::sort는 대상 범위 [first, last)의 요소들을 정렬해요. 동등한 요소의 순서는 보존되지 않을 수 있어요. 순서 보존이 필요하면 std::stable_sort를 써요.

출처: cppreference

본문

std::sort는 대상 범위 [first, last)의 요소들을 오름차순으로 정렬해요. 동등한 요소들의 순서는 보존되지 않을 수 있어요. <algorithm> 헤더에 정의되어 있어요.

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

template< class RandomIt, class Compare >
void sort( RandomIt first, RandomIt last, Compare comp );
  • 1번 오버로드 — 요소를 operator<(즉 std::less{})를 기준으로 정렬해요.
  • 2번 오버로드 — 요소를 비교 함수 comp를 기준으로 정렬해요.
  • 병렬 실행 정책을 받는 오버로드도 있어요.

복잡도 (Complexity)

Nstd::distance(first, last)라고 하면 𝓞(N·log N)번의 비교가 평균적으로 필요해요.

예제 (Example)

#include <algorithm>
#include <iostream>
#include <vector>

int main()
{
    std::vector<int> v{5, 2, 8, 1, 9, 3};
    std::sort(v.begin(), v.end());
    for (int x : v) std::cout << x << ' ';
    std::cout << '\n';
}

출력:

1 2 3 5 8 9

더 알아보기 (Learn more)

cppreference