插入排序是低級排序中比較快的一種,原理是,將數據分爲內外兩部分,內部初始爲一個數據,將外部數據插入內部,插入的原則是比後面的小,比前面的大。
代碼如下(c編寫)
#include<stdio.h>
void insertionsort(int *a,int n);
void main()
{
int a[10]={7,2,1,3,6,5,0,9,8,4};
int j;
insertionsort(a,10);
for(j=0;j<10;j++)
{
printf("%d\n",a[j]);
}
}
void insertionsort(int *a,int n)
{
int in,out,temp;
for(out=1;out<n;out++)
{
temp=a[out];
in=out;
while(in>0 && a[in-1]>=temp)
{
a[in]=a[in-1];
in--;
}
a[in]=temp;
}
}