排序之插入排序

  1.  
  2.    1.
  3.    2. /*
  4.    3. * 算法思想:跟玩扑克牌时自己整理牌的思想是一样的.
  5.    4. *         首先,只有一张牌,可看做是已有序了.
  6.    5. *         然后,每进来一张牌(第N张牌),就需要在前面已有序的(N-1)张
  7.    6. *         牌进行扫描,找到自己应该插入的位置. 然后插入.
  8.    7. */
  9.    8.
  10.    9. //input: array name and the length of the array.
  11.   10. //output: void.
  12.   11. void insert_sort(int array[], int n)
  13.   12. {
  14.   13.     int i;      //i is the index of going to be sorted number.
  15.   14.     int j;      //j is the index of sorted numbers.
  16.   15.     int key;    //the key number which is going to be sorted.
  17.   16.   //外循环从1开始.array[0]默认是已有序了.只需要把后面的n-1个数进行排序即可         
  18.    1.     for (i=1; i<n; i++)
  19.    2.     {
  20.    3.         key = array[i];
  21.    4.                 j=i-1;
  22.    5.   //顺序扫描前面已有序的数组,查找到需要插入的正确位置.
  23.    6.         while (j>=0 && key<array[j])
  24.    7.         {
  25.    8.                   array[j+1] = array[j];
  26.    9.                   j--;
  27.   10.         }//while
  28.   11.
  29.   12.                 //insert the array[i] into the correct position.
  30.   13.                 array[j+1] = key;
  31.   14.         
  32.   15.     }//for
  33.   16. }//insert-sort()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值