목차.

  1. 개요
  2. 오름차순 정렬
  3. 내림차순 정렬
  4. 클래스를 사용한 정렬

 

개요

 

C++ STL에서 'std::sort' 함수는 배열 또는 컨테이너의 요소를 정렬하는 데 사용되며, 효율적인 정렬 알고리즘을 구현하고 있습니다.

sort 함수는 인트로 소트(Intro Sort)와 같은 정렬 알고리즘을 구현하고 있어 대용량 데이터셋에도 높은 성능을 보이고 있습니다.

시간 복잡도는

퀵소트(Quick Sort) : 최악 : O(n^2), 최선 :O(n log n)

인트로 소트(Intro Sort) : 최악, 최선:O(n log n)

sort 함수 : 최선, 최악 : O(n log n)

 

즉 인트로 소트와 같은 시간복잡도를 가집니다.

 

오름차순 정렬

 

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

using namespace std;

int solution(vector<int> array) {
// array에 3 5 7 1 
    sort(array.begin(), array.end());
// array에 1 3 5 7
    return answer;
}

 

sort 함수를 사용하기 위해서 algorithm 헤더를 포함해야 합니다.

 

내림차순 정렬

 

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

using namespace std;

bool compare(int a, int b) {
    return a > b; // 내림차순으로 정렬하려면 '>' 연산자를 사용
}

int solution(vector<int> array) {
// array에 3 5 7 1 
    sort(array.begin(), array.end(), compare); // 내림차순으로 정렬
// array에 7 5 3 1
    return answer;
}

 

내림차순은 compare 함수에서 a가 b보다 크면 true를 반환하도록 정의했습니다.

 

클래스를 사용한 정렬

 

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

class Student {
	
public:
	Student(string name, int score) {
		this->name = name;
		this->score = score;
	};
	string name;
	int score;
	bool operator <(Student& student) {
		return this->score < student.score;
	}
};

int main(void) 
{
	Student students[] = {
		Student("김철수",90),
		Student("김미애",85),
		Student("홍길동",100),
	};
	sort(students, students + 3);
	for (int i = 0; i < 3; i++)
	{
		cout << students[i].name << " ";
	}
	return 0;
}

 

위 코드에서 주목할 부분은 operator라는 bool형 함수를 통해서 데이터를 정렬한다는 점입니다.

+ Recent posts