1、算法原理
插入排序是最简单的一种排序算法。插入排序由N-1趟排序组成。对于P=1趟到P=N-1趟,插入排序保证从位置0到位置P上的元素为已排序状态。插入排序利用了这样的事实:位置0到位置P-1上的元素是已排序的。
2、代码(C版)
/*+++++++++++++++++++++++++++++++++++++++++++++
+ 插入排序(C版)
+
+
+author:zhouyongxyz 2013-4-14 16:57
++++++++++++++++++++++++++++++++++++++++++*/
#include <cstdio>
#define N 9
typedef int ElementType;
void InsertSort(ElementType a[],int n);
int main()
{
int a[N]={4,2,1,3,5,6,8,9,7};
InsertSort(a,N);
for(int i=0;i<N;i++)
printf("%d ",a[i]);
printf("\n");
return 0;
}
void InsertSort(ElementType a[],int n)
{
int i,P;
int tmp;
for(P=1;P<n;P++)
{
tmp=a[P];
for(i=P;i>0&&tmp<a[i-1];i--)
a[i]=a[i-1];
a[i]=tmp;
}
}