選擇排序
1)原理:對於一個將要排序的數組A[n],先找出最小元素(升序排列),將其與A[0]交換,接着在數組下標爲1~n-1的元素中尋找最小值,與A[1]交換,直到排序結束。
2)C語言實現:
void main()
{
int t,temp,count, *p;
printf("please input the count :");
scanf_s("%d", &count);
p = (int *)malloc(count * 2);
printf("\nplease input the number to be sorted : \n");
for (int i = 0; i < count; i++)
{
scanf_s("%d", p+i);
}
for (int i = 0; i < count; i++)
{
t = i;
for (int j = i+1; j < count; j++)
{
if (p[t] > p[j])
{
t = j;
}
}
temp = p[t];
p[t] = p[i];
p[i] = temp;
}
for (int i = 0; i < count; i++)
{
printf("%d ", p[i]);
}
system("pause");
}
3)分析:
- 最好情況(序列已經有序) :在這種情況下,選擇排序只需要將整個序列遍歷一遍即可。故時間複雜度爲O(n),爲線性時間複雜度。
- 最壞情況:每次遍歷尋找最小元素A[i]時都需要從i尋找到最後一個元素,例如:2,3,4,5,6,7,8,9,1,在進行選擇排序的時候很是吃虧,其時間複雜度爲O(n^2)。
- 平均情況:隨機選擇n個數來進行插入排序,每次尋找最小的元素大概能在中間的位置找到,平均時間複雜度也是O(n^2)。