Cpp에서 Sort - fora22/CodingTest GitHub Wiki

Cpp에서 Sort

  • <algorithm> header의 sort 알고리즘을 사용한다.
  • qucik sort를 기반으로 구현되어 있으며 평균 시간 복잡도는 n log n이다.

배열

#include<iostream>
#include<algorithm>
using namespace std;

int main(void){
    int arr[10] = {3, 7, 2, 4, 1, 0, 9, 8, 5, 6};

    sort(arr, arr+10); //[arr, arr+10) default(오름차순)로 정렬
    
    return 0;
}

vector container

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

using namespace std;

int main(void){
    srand((int)time(NULL)); //난수생성을 위해
    
    vector<int> v = {3, 7, 2, 4, 1, 0, 9, 8, 5, 6};
    sort(v.begin(), v.end());       // 오름차순으로 정렬, default 값
    sort(v.begin(), v.end(), greater<int>()); // 내림차순으로 정렬
    
    return 0;
}

사용자 정의 sort

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

using namespace std;

bool compare(int a, int b) {
    return a < b;   // 오름차순
    return a > b;   // 내림차순
}

int main(void){
    srand((int)time(NULL)); //난수생성을 위해
    
    vector<int> v = {3, 7, 2, 4, 1, 0, 9, 8, 5, 6};
    sort(v.begin(), v.end(), compare);
    
    return 0;
}

사용자 정의 sort(유명한 Class Student)

#include<iostream>
#include<algorithm>
#include<vector>
#include<ctime>
using namespace std;
 
 
class Student{
public:
    string name;
    int age;
    Student(string name, int age):name(name),age(age){}
    
};
 
 
void Print(vector<Student> &v){
    cout << "Student : " ;
    for(int i=0; i<5; i++){
        cout << "[" << v[i].name << ", " << v[i].age << "]";
    }
    cout << endl;
}
 
bool compare(Student a, Student b){
    if(a.name == b.name){   //이름이 같으면, 나이가 적은순
        return a.age < b.age;
    }else{                  //이름 다르면, 이름 사전순
        return a.name < b.name;
    }
    
}
int main(void){
    vector<Student> v;
    
    v.push_back(Student("cc", 10));
    v.push_back(Student("ba", 24));
    v.push_back(Student("aa", 11));
    v.push_back(Student("cc", 8));  //cc는 이름이 같으니 나이 기준 오름차순 예시
    v.push_back(Student("bb", 21));
    
    Print(v); //정렬 전 출력
    sort(v.begin(), v.end(), compare); //[begin, end) compare 함수 기준 정렬
    Print(v); //정렬 후 출력
    
    return 0;
}

Reference

⚠️ **GitHub.com Fallback** ⚠️