IT&컴퓨터공학/자료구조&알고리즘

[C++] 내림차순 정렬하기

yan_z 2021. 1. 11. 12:05

 

정렬

: sort() 함수 이용

 

- #include <algorithm> 선언해줘야함

- 퀵소트로 구현되어있어 빠른 속도로 정렬함

- 기본적으로는 오름차순으로 정렬을 해줌 ex) 1,2,3,4,5,6

- 사용법 : sort(v.begin(),v.end());

 

→ 내림차순으로 정렬하고싶을땐 어떻게 할까 ?

 

 

1. 비교함수를 만들어서 인수로 주자 ( return 형은 bool )

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

using namespace std;

bool compare(int a ,int b) { // 비교함수 
	return a > b;
}

void main() {
	vector<int> num = { 1,2,3,4,5 };
	sort(num.begin(), num.end(), compare);

	for (auto n : num) cout << n << endl;
    
    // 결과 : 5 4 3 2 1
}

- compare 라는 비교함수를 직접 만들고 인자로 넣어주면 내림차순으로 정렬가능

- 마찬가지로 어떤 정렬 조건을 직접 정하고싶으면 이렇게 비교함수를 직접 만들면 된다.

 

2. rbegin () , rend() 이용

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

using namespace std;

void main() {
	vector<int> num = { 1,2,3,4,5 };
	sort(num.rbegin(), num.rend());

	for (auto n : num) cout << n << endl;
}

 

3. reverse 함수 이용

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

using namespace std;

void main() {
	vector<int> num = { 1,2,3,4,5 };
	reverse(num.begin(), num.end());

	for (auto n : num) cout << n << endl;
}