直接选择排序算法是一种简单的排序算法,它的时间复杂度为O(N^2),空间复杂度为O(1),它的时间复杂度与初始状态无关,因此总是做一些“重复性”的动作,并且它是不稳定的。
直接选择排序算法的实现:
template <typename T>
void SelectSort(T *array, const int size)
{
assert(NULL != array && size > 0);
if(size == 1)
return;
for(int i = 0; i < (int)size-1; i++)
{
int sub = i;
for(int j = i+1; j < (int)size; j++)
if(Less<T>()(array[j], array[sub]))
sub = j;
if(sub != i)
swap(array[i], array[sub]);
}
}
测试代码:
void test4()
{
int arr[100] = { 0 };
int sz = sizeof(arr) / sizeof(arr[0]);
srand((unsigned int)time(0));
for(int i = 0; i < sz; i++) //Assign values with random numbers
{
arr[i] = rand() % sz;
}
for(int i = 0; i < sz; i++) //print array
cout << arr[i] << " ";
cout << endl << endl << endl << "sort:" << endl;
SelectSort(arr, sz);
for(int i = 0; i < sz; i++) //print array
cout << arr[i] << " ";
cout << endl;
for(int i = 1; i < sz; i++) //check that the sort is correct
{
if(Less<int>()(arr[i], arr[i-1]))
cout << "insert sort error! " << i << endl;
}
}
测试结果:
排序正确!