#include<stdio.h>
#define N 10
int source[N] = {1,5,3,2,7,9,4,10,6,8};
int main()
{
int j;
for(j=1;j < N;j++)
{
int i = j - 1;
int key = source[j];
while(i >= 0 && source[i] > key)
{
source[i+1] = source[i];
i = i - 1;
}
source[i+1] = key;
}
for(j = 0; j < N;j++)
printf("%d ",source[j]);
printf("\n");
return 0;
}
bubble sort 源码
与插入排序相似,最坏情况下,时间复杂度为 O(n^2)
最好去况下的时间复杂度为 O(n)
其平均的时间复杂度为 O(n^2)
但其无须额外的空间进行辅助排序 故空间复杂度为 O(1)