选择排序,顾名思义,指从数组后面将最小的值找出来,然后与最前面(指当前位置)值进行交换。
时间复杂度:O(n^2)
空间复杂度:O(1)
此处应用了C++11的auto , lambda , static_assert 。
show me the code !
// #if __cplusplus < 201103L // #error "must be compiled under c++11 support platform!!!" // #endif #include <iostream> #include <algorithm> #include <iterator> #include <cassert> using namespace std; void Swap(int& a, int& b) { int tmp = a; a = b; b = tmp; } void SelectSort(int varList[], const int size) { if (!varList || size <= 1) { return; } for (int i = 0; i < size; i++) { int swapPos = i; for (int j = i; j < size; j++) { if (varList[swapPos] > varList[j]) { swapPos = j; } } if (i != swapPos) { Swap(varList[i], varList[swapPos]); } } } void test() { //case counter int testCase = 0; //sort function object auto sortFunc = SelectSort; //show case result lambda function auto showFunc = [&testCase](const char* caseDescription){cout << "case[" << testCase++ << "]\t(" << caseDescription << ") \t\tok " << endl; }; cout << "test begin : " << endl << endl; //case empty list { sortFunc(nullptr, 0); showFunc("case empty list"); } //case wrong size { int nTestList[] = { 13, 52, 32, 15, 66, 2, 99, 202, 103, 2 }; sortFunc(nTestList, 0); showFunc("case wrong size"); } //case size == 1 { int var = 13; int varList[] = { var }; sortFunc(varList, 1); assert(var == varList[0]); showFunc("case size == 1"); } //case normal sort { int varList[] = { 13, 52, 32, 15, 66, 2, 99, 202, 103, 2 }; const int size = sizeof(varList) / sizeof(int); const int resultList[] = { 2, 2, 13, 15, 32, 52, 66, 99, 103, 202 }; static_assert(sizeof(varList) == sizeof(resultList), "size of varList is not equal with resultList!!"); sortFunc(varList, size); for (int i = 0; i < size; i++){ assert(varList[i] == resultList[i]); } showFunc("case normal sort"); } //case sorted list { int varList[] = { 2, 2, 13, 15, 32, 52, 66, 99, 103, 202 }; const int size = sizeof(varList) / sizeof(int); const int resultList[] = { 2, 2, 13, 15, 32, 52, 66, 99, 103, 202 }; static_assert(sizeof(varList) == sizeof(resultList), "size of varList is not equal with resultList!!"); sortFunc(varList, size); for (int i = 0; i < size; i++){ assert(varList[i] == resultList[i]); } showFunc("case sorted list"); } cout << endl << "test done ! " << endl << endl; } int main(int argc, char* argv[]) { test(); return 0; }