插入排序,對於少量元素的排序,是一個有效的算法。將其僞代碼過程命名爲INSERTION-SORT,其中的參數是一個數組A[1..n],包含長度爲n的要排序的一個序列。
僞代碼如下:
INSERTION-SORT(A)
for j = 2 to A.length
key = A[j]
// Insert A[j] into thesorted sequence A[1..j - 1]
i = j – 1
while i > 0 and A[j]> key
A[i+1] = A[i]
i = i – 1
A[i+1] = key
代碼實現如下:
#include <stdio.h>
void main()
{
inta[]={2,3,9,4,1,8,5,7,6,0};
inti,j,temp;
for(i=1;i<10;i++)
{
temp=a[i];
j=i-1;
while(j>=0&& a[j]>temp)
{
a[j+1]=a[j];
j=j-1;
}
a[j+1]=temp;
}
printf("sortnumber:\n");
for(i=0;i<10;i++)
{
printf("%4d",a[i]);
}
printf("\n");
}