C++/C++ 문법
sort() 함수 사용법
GREEN나무
2025. 3. 23. 18:49
728x90
sort() 함수
📌 sort() 함수란?
sort() 함수는 C++의 <algorithm> 헤더에 포함된 정렬 함수입니다.
- 퀵 정렬(Quick Sort) 기반으로 동작하며, 평균 시간 복잡도는 O(N log N)입니다.
- 최악의 경우 O(N²)이지만, 일반적으로 안정적이고 빠릅니다.
✅ 함수 원형
template <typename RandomIt>
void sort(RandomIt first, RandomIt last);
template <typename RandomIt, typename Compare>
void sort(RandomIt first, RandomIt last, Compare comp);
- first: 정렬 시작 위치 (begin() 사용)
- last: 정렬 끝 위치 (end() 사용)
- comp: 사용자 정의 비교 함수나 조건자
sort() 사용 예제
📌 1. 기본 정렬 (오름차순)
#include <iostream>
#include <algorithm>
using namespace std;
int main() {
int arr[5] = {4, 2, 7, 1, 9};
sort(arr, arr + 5); // 기본 오름차순 정렬
for (int i : arr) cout << i << " "; // 1 2 4 7 9
}
📌 2. 내림차순 정렬
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main() {
vector<int> vec = {3, 8, 2, 7, 4};
sort(vec.begin(), vec.end(), greater<int>()); // greater<int>() 활용
for (int i : vec) cout << i << " "; // 8 7 4 3 2
}
- greater<int>(): 큰 값을 앞으로 정렬 (내림차순)
- less<int>(): 작은 값을 앞으로 정렬 (오름차순, 기본값)
📌 3. 사용자 정의 비교 함수 사용
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
bool compare(int a, int b) {
return (a % 10) < (b % 10); // 일의 자리 기준 오름차순
}
int main() {
vector<int> vec = {43, 25, 71, 82, 56};
sort(vec.begin(), vec.end(), compare);
for (int i : vec) cout << i << " "; // 71 82 43 25 56
}
- compare() 함수는 a % 10을 기준으로 일의 자리 숫자를 비교합니다.
📌 4. 클래스 객체 정렬
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
class Student {
public:
string name;
int age;
Student(string n, int a) : name(n), age(a) {}
};
// 비교 함수: 나이 기준으로 정렬
bool compare(Student a, Student b) {
return a.age < b.age;
}
int main() {
vector<Student> students = { {"John", 20}, {"Alice", 22}, {"Bob", 18} };
sort(students.begin(), students.end(), compare);
for (auto& s : students) cout << s.name << " (" << s.age << ") ";
}
- 결과: Bob (18) John (20) Alice (22)
- 사용자 정의 객체를 정렬할 때는 compare() 함수로 조건을 설정합니다.
정리
- 오름차순 정렬: sort(vec.begin(), vec.end());
- 내림차순 정렬: sort(vec.begin(), vec.end(), greater<int>());
- 사용자 정의 함수 정렬: sort(vec.begin(), vec.end(), compare);
- 객체 정렬: 사용자 정의 비교 함수를 사용하거나 연산자 오버로딩 활용
참고
https://com24everyday.tistory.com/entry/C-Sort-%EC%82%AC%EC%9A%A9
https://husk321.tistory.com/363
https://breakcoding.tistory.com/117