选择排序,顾名思义,指从数组后面将最小的值找出来,然后与最前面(指当前位置)值进行交换。

时间复杂度: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 <= )
{
return;
}
for (int i = ; 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 = ;
//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, );
showFunc("case empty list");
}
//case wrong size
{
int nTestList[] = { , , , , , , , , , };
sortFunc(nTestList, );
showFunc("case wrong size");
}
//case size == 1
{
int var = ;
int varList[] = { var };
sortFunc(varList, );
assert(var == varList[]);
showFunc("case size == 1");
}
//case normal sort
{
int varList[] = { , , , , , , , , , };
const int size = sizeof(varList) / sizeof(int);
const int resultList[] = { , , , , , , , , , };
static_assert(sizeof(varList) == sizeof(resultList), "size of varList is not equal with resultList!!"); sortFunc(varList, size);
for (int i = ; i < size; i++){ assert(varList[i] == resultList[i]); }
showFunc("case normal sort");
}
//case sorted list
{
int varList[] = { , , , , , , , , , };
const int size = sizeof(varList) / sizeof(int);
const int resultList[] = { , , , , , , , , , };
static_assert(sizeof(varList) == sizeof(resultList), "size of varList is not equal with resultList!!"); sortFunc(varList, size);
for (int i = ; 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 ;
}
05-18 03:16