Chinaunix首页 | 论坛 | 博客
  • 博客访问: 743975
  • 博文数量: 141
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 1115
  • 用 户 组: 普通用户
  • 注册时间: 2014-03-17 14:32
个人简介

小公司研发总监,既当司令也当兵!

文章分类

全部博文(141)

分类: LINUX

2016-02-16 15:32:30

插入排序

就是每一步都将一个待排数据按其大小插入到已经排序的数据中的适当位置,直到全部插入完毕。 
插入排序方法分直接插入排序和折半插入排序两种,这里只介绍直接插入排序,折半插入排序留到“查找”内容中进行。 
  图1演示了对4个元素进行直接插入排序的过程,共需要(a),(b),(c)三次插入。


实现代码:

点击(此处)折叠或打开

  1. void insertSort(int list[], int len)
  2. {
  3.     int index = 1;
  4.     int insertKey;
  5.     int cursor;

  6.     if (len <= 1)
  7.         return;

  8.     for (index = 1; index < len; index++)
  9.     {
  10.         insertKey = list[index];
  11.         cursor = index - 1;
  12.         
  13.         while (cursor >= 0)
  14.         {
  15.             if (list[cursor] > insertKey)
  16.             {
  17.                 list[cursor + 1] = list[cursor];
  18.                 cursor--;
  19.                 continue;
  20.             }
  21.             else
  22.             {
  23.                 list[cursor + 1] = insertKey;
  24.                 break;
  25.             }
  26.         }
  27.         if (cursor < 0)
  28.             list[cursor + 1] = insertKey;
  29.     }
  30. }


阅读(1889) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~