直接插入排序算法--c语言实现

   /*直接插入排序的思想就是从数组的第二个元素开始,每次和其前面的元素比较,插入到合适的位置,每次插入后前面的元素都是一个有序的数组。*/
</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;    
    }
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值