插入排序

参考:

《linux c编程一站式学习》的例11.1

思想:

  插入排序类似于玩扑克牌时的抓牌过程,玩家每拿到一张牌都要将其插入手中已有的牌里,使之从小到到大排序

code:

 1 #include <stdio.h>
 2 
 3 #define LEN 5
 4 int testData[LEN] = {10, 5, 2, 4, 7};
 5 
 6 void insertion_sort(void)
 7 {//从小到大排序,下标0的位置保存最小值
 8     int i, j;
 9     int key; //好比是新拿到的那张牌
10     for(i=1; i<LEN; i++){
11         printf("%d, %d, %d, %d, %d\n", testData[0], testData[1], testData[2], testData[3], testData[4]);
12         key =  testData[i];
13         for(j=i-1; j>=0; j--){
14             if(key > testData[j])
15                 break;//当前牌的值比前面最后牌的值大,则跳出循环(因为前面是已经排好序的数据)
16             testData[j+1] = testData[j]; //否则需要向后挪一个位置,留出空间插入新牌
17         }
18         testData[j+1] = key;//插入新牌
19     }
20     printf("%d, %d, %d, %d, %d\n", testData[0], testData[1], testData[2], testData[3], testData[4]);
21 }
22 
23 int main(int argc, char *argv[])
24 {
25     insertion_sort();
26     return 0;
27 }

截图:

转载于:https://www.cnblogs.com/shanyu20/p/10932142.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值