插入排序

参考:

《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 }

截图:

posted @ 2019-05-27 17:56  shanyu20  阅读(252)  评论(0编辑  收藏  举报