sort()

김민수·2025년 1월 8일

C++

목록 보기
38/68

컨테이너의 요소를 정렬하는데 사용되는 알고리즘 함수이다.
std::sort는 빠른 정렬(퀵 정렬, 힙 정렬, 삽입 정렬을 혼합한 하이브리드 정렬 알고리즘)로 구현되어 있으며, 시간 복잡도는 평균적으로 O(n log n)이다.


1. 함수 매개변수

#include <algorithm>

std::sort(시작_반복자, 끝_반복자, [비교_함수]);
  • 시작_반복자: 정렬을 시작할 위치
  • 끝_반복자: 정렬이 끝나는 위치(포함되지 않음)
  • 비교_함수: 선택 사항. 커스텀 비교 기준 제공
    -아무것도 안 적었을 때 - 오름차순
    -std::less<> - 오름차순
    -std::greater<> - 내림차순


2. 기본 정렬 (오름차순 정렬)

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

int main() {
    std::vector<int> vec = {5, 2, 9, 1, 5, 6};

    // 기본 오름차순 정렬
    std::sort(vec.begin(), vec.end());

    // 출력
    for (int num : vec) {
        std::cout << num << " ";
    }

    return 0;
}


3. 내림차순 정렬 (std::greater<> 사용)

#include <iostream>
#include <algorithm>
#include <vector>
#include <functional> // std::greater 사용 시 필요

int main() {
    std::vector<int> vec = {5, 2, 9, 1, 5, 6};

    // 내림차순 정렬
    std::sort(vec.begin(), vec.end(), std::greater<>());

    // 출력
    for (int num : vec) {
        std::cout << num << " ";
    }

    return 0;
}


4. 사용자 정의 비교 함수 (짝수 우선 정렬)

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

// 짝수를 우선 정렬하는 비교 함수
bool customCompare(int a, int b) {
    if (a % 2 == 0 && b % 2 != 0) return true;  // 짝수를 우선
    if (a % 2 != 0 && b % 2 == 0) return false; // 홀수는 나중
    return a < b; // 같은 성격(짝수/홀수)일 경우 오름차순 정렬
}

int main() {
    std::vector<int> vec = {5, 2, 9, 1, 5, 6, 8};

    // 사용자 정의 비교 함수 사용
    std::sort(vec.begin(), vec.end(), customCompare);

    // 출력
    for (int num : vec) {
        std::cout << num << " ";
    }

    return 0;
}


5. 문자열 정렬 (길이 기준 정렬)

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

// 문자열 길이를 기준으로 정렬하는 비교 함수
bool lengthCompare(const std::string &a, const std::string &b) {
    return a.length() < b.length();
}

int main() {
    std::vector<std::string> vec = {"apple", "kiwi", "banana", "grape", "pear"};

    // 문자열 길이 기준 정렬
    std::sort(vec.begin(), vec.end(), lengthCompare);

    // 출력
    for (const std::string &str : vec) {
        std::cout << str << " ";
    }

    return 0;
}


6. 람다 함수 사용 (내림차순 정렬)

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

int main() {
    std::vector<int> vec = {5, 2, 9, 1, 5, 6};

    // 람다 함수로 내림차순 정렬
    std::sort(vec.begin(), vec.end(), [](int a, int b) {
        return a > b;
    });

    // 출력
    for (int num : vec) {
        std::cout << num << " ";
    }

    return 0;
}
profile
안녕하세요

0개의 댓글