/*****************************************************
* insertion_sort.c *
* Sort N numbers by INSERTION_SORT *
* by pdcxs *
* time:2012-12-23 *
*****************************************************/
#include<stdio.h>
#include<stdlib.h>
#define N 5
int main(void){
int num[N], i, j, key;
printf("Please input %d numbers:\n", N);
for(i = 0; i < N; i++)
scanf("%d", num + i);
for(i = 1; i < N; i++){
key = num[i];
j = i-1;
while(j >= 0 && num[j] >= key){
num[j+1] = num[j];
j--;
}
num[j+1] = key;
}
for(i = 0; i < N; i++)
printf("%d\t", num[i]);
printf("\n");
system("pause");
return 0;
}
插入排序关键:
和起牌一样,当前排用变量key保存,然后前面各张排往后移,给当前牌(key)腾出合适的位置,然后把key插到该位置中去。