sort
sort (정렬)
범위를 비감소 순서로 정렬하는 기본 정렬 알고리즘이에요. <algorithm> 헤더에 있어요.
출처: cppreference
본문
sort는 범위 [first, last)를 오름차순(비감소)으로 정렬해요.
template< class RandomIt >
void sort( RandomIt first, RandomIt last ); // (1)
비교기 버전도 있어요.
template< class RandomIt, class Compare >
void sort( RandomIt first, RandomIt last, Compare comp ); // (2)
-
operator<로, 2)comp로 비교해요.
- 복잡도: 평균
O(N·log N)번의 비교.
std::vector<int> v{3, 1, 4, 1, 5, 9, 2};
std::sort(v.begin(), v.end());
// v == {1,1,2,3,4,5,9}
// 내림차순
std::sort(v.begin(), v.end(), std::greater<int>());
sort는 안정적이지 않아요(같은 값의 상대 순서를 보장하지 않음). 안정 정렬이 필요하면 std::stable_sort를 써요. std::list같은 노드 컨테이너는 자체 sort 멤버를 쓰는 게 좋아요.