/*直接插入排序的思想就是从数组的第二个元素开始,每次和其前面的元素比较,插入到合适的位置,每次插入后前面的元素都是一个有序的数组。*/
</pre><pre name="code" class="cpp">/*********************直接插入排序********************/
#include <stdio.h>
#define ARRSIZE 10
void sort(int *,int);
void print_array(int *);
int main()
{
int array[ARRSIZE]={1,3,4,5,8,7,9,0,2,6};
sort(array,ARRSIZE);
print_array(array);
return 0;
}
void print_array(int *arr)
{
int fact = 0;
printf("\n--------------- after sort ----------------------------------\n");
for(fact = 0; fact < ARRSIZE; fact++){
printf("%4d",arr[fact]);
}
printf("\n-------------------------------------------------------------\n");
}
void sort(int *arr,int size)
{
int i = 0;
int j = 0;
int fact = 0; /*数组元素要移动的偏移量*/
int cnt = 0;
int temp = 0;
for(i = 1; i < size; i++){
temp = arr[i];
for(j = i-1; j >=0; j--){
if(arr[i] > arr[j]){ /*如果要插入的数据比有序数组最大的元素大*/
break; /*则跳出循环*/
}else{
fact++;
}
}
for(cnt=0;cnt<fact;cnt++){
arr[i-cnt]=arr[i-cnt-1]; /*移动数组*/
}
arr[i-fact]=temp;
fact = 0;
}
}