컴퓨터/C++
[정렬][C++] Template를 이용한 버블 정렬(Bubble Sort)
Luyin
2013. 1. 30. 22:59
Bubble Sort(버블 정렬)
C++, Array Version (배열 버전)
Bubble Sort Function(버블 정렬 함수)
template<typename T, size_t n>void sort_bubble(T (&_input)[n], bool _option) { int length = sizeof(_input) / sizeof(_input[0]); for(int i=0; i<length;i++) { for(int j=i; j<length-1; j++) { if(_option) //오름차순 { if(_input[j] > _input[j+1]) { swap(_input[j], _input[j+1]); } }else{ //내림차순 if(_input[j] < _input[j+1]) { swap(_input[j], _input[j+1]); } } } } } |
예제)
#define Ascending true #define Descending false int main(void) { char test[] = {'a', 'c', 'a', 'f', 'd'}; sort_bubble(test, Ascending); for(int i=0; i<7; i++) { cout <<test[i]<<endl; } } |