选择排序是冒泡排序的一种优化!
将数组分为两部分,一部分是已经排好序的,另一部分是未排好序的,每次找数组后半部分中最小的一个元素排到
前面的序列中!
时间复杂度为(n-1) + (n-2) + ... + 2 + 1 = n(n-1)/2;
#include <stdio.h>
void selectSort(int arr[], int size)
{
int pos1 = 0, pos2 = 0;
for(pos1 = 0; pos1 < size-1; ++pos1)
{
int tempos = pos1;
//内循环每次负责找到最小数的下标
for(pos2 = pos1+1; pos2 < size; ++pos2)
{
if(arr[pos2] < arr[tempos])
{
tempos = pos2;
}
}
if(tempos != pos1)
{
int temp = arr[pos1];
arr[pos1] = arr[tempos];
arr[tempos] = temp;
}
}
}
int main()
{
int arr[] = {-3,-5,0,-2,5,1,6,-2,8,7,-9,20};
int i = 0;
selecttSort(arr, 12);
for(i = 0; i < 12; ++i)
{
printf("%d ",arr[i]);
}
printf("\n");
return 0;
}