c语言描述的直接插入排序法

时间:2022-08-19 04:32:45
#include<stdio.h>
#include
<stdlib.h>
#define SIZE 6
typedef
int Type;
//直接插入排序法
void InsertSort(Type a[],Type n){
int i,j;
int temp;
for(i=1;i<n;i++){
j
=i-1;
temp
=a[i];//如果不使用中间变量,那么在移动后的a[i]会改变!
while((j>=0)&&(temp<a[j])){//后移比当前插入的值要大的
a[j+1]=a[j];
j
--;
}
a[j
+1]=temp;//把当前插入的值放到j+1的位置,他前面的都要比他小,后面的都比他大
}
for(i=0;i<n;i++){
printf(
"%d\n",a[i]);
}
}
void main(){
int a[SIZE]={1,5,3,4,6,7};
InsertSort(a,SIZE);

}