插入排序时间复杂度为 O(N*N)
核心代码如下:
#include <stdio.h>
/**
* 插入排序
* smileyan
*/
typedef int ElemType;
bool InsertSort(ElemType ary[],int n)
{
if(n==0)
return false;
int i,j;
ElemType tmp;
for(i=1; i<n; i++)
{
tmp=ary[i]; //记录ary[i]
// 进行比较 排序
for(j=i; j>0&&ary[j-1]>tmp; j--)// 从ary[i]开始向左边进行比较
{
ary[j] = ary[j-1];
}
// 插入到此位置
ary[j]=tmp;
}
return true;
}
int main()
{
ElemType ary[5]= {8,3,6,4,2};
InsertSort(ary,5);
for(int i=0; i<5; i++)
{
printf("%d ",ary[i]);
}
return 0;
}