제네릭 정렬 알고리즘:
STL은 sort(퀵 정렬), stable_sort(합병 정렬), partial_sort(힙 정렬), 이 세 개의 제네릭 정렬 알고리즘을 제공한다.
이들 각각은 임의접근 시퀀스를 정렬하며, 정렬 결과는 알고리즘이 적용된 컨테이너 내에 반영된다. (이러한 알고리즘을 in-place 알고리즘이라고 한다.)

특징:
. 평균적인 소요시간이 중요할 때에는 sort를 사용한다.
. 최악조건에서의 소요시간이 중요하다면 stable_sort나 partial_sort를 사용한다.
. 국가-지역 필드 혹은 동명이인 필드를 정렬해야 하는 경우, 안정 정렬(stable_sort)을 사용하는 것이 빠르다.
. 안정 정렬(stable_sort) 은 값이 같다면 원래의 순서를 보장한다.
. 불안정 정렬(sort, partial_sort) 은 값이 같아도 원래의 순서를 보장하지 않는다.


http://codepad.org/mvzfPVBS
#include <iostream>
#include <algorithm>
#include <boost/array.hpp>
#include <functional>

using namespace std;

#define CONTAINER boost::array<int, 10>
#define CONTAINER_ITER  CONTAINER::iterator

void print( const char* str, CONTAINER_ITER begin, CONTAINER_ITER end)
{
	cout << str;
	copy(begin, end, ostream_iterator<int>(cout, " "));
	cout << endl;
}

int main()
{
	CONTAINER c;
	CONTAINER_ITER iter = c.begin();
	int cnt = 0;
	
	//Init
	for(; iter != c.end() ; ++iter)
		*iter = cnt++;
	random_shuffle(c.begin(), c.end());
	print("Original             : ", c.begin(), c.end());

	//sort
	sort(c.begin(), c.end());
	print("sort - normal        : ", c.begin(), c.end());

	//sort with Greater
	sort(c.begin(), c.end(), greater<int>());
	print("sort - with greater  : ", c.begin(), c.end());

	//sort with Less
	sort(c.begin(), c.end(), less<int>());
	print("sort - with less     : ", c.begin(), c.end());

	return 0;
}


Output:
1
2
3
4
Original             : 4 3 7 8 0 5 2 1 6 9 
sort - normal        : 0 1 2 3 4 5 6 7 8 9 
sort - with greater  : 9 8 7 6 5 4 3 2 1 0 
sort - with less     : 0 1 2 3 4 5 6 7 8 9 



+ Recent posts