Chinaunix首页 | 论坛 | 博客
  • 博客访问: 146619
  • 博文数量: 28
  • 博客积分: 1646
  • 博客等级: 上尉
  • 技术积分: 405
  • 用 户 组: 普通用户
  • 注册时间: 2007-03-12 14:28
文章分类

全部博文(28)

文章存档

2013年(28)

我的朋友

分类: C/C++

2013-03-11 17:42:36

插入排序原理:
将待排序的集合分为两个子集,一个是已排序子集,一个是未排序子集。插入排序的过程就是从未排序子集中逐个取出元素插入到已排序子集中。
集合可以是数组,也可以是链表。
插入排序的时间复杂度是O(n*n)。

插入排序算法实现:

点击(此处)折叠或打开

  1. /*
  2.  * insertion sort
  3.  * It splits the array into two arrays, one is in order, the other is not.
  4.  * The sort process will get the element from the unsorted array one by one,
  5.  * then insert it into the sorted array.
  6.  */
  7. void insertion_sort(int a[], int size)
  8. {
  9.     int i, j;
  10.     int tmp;

  11.     /* i starts from 1, not 0, because a[0] is in order */
  12.     for (i=1; i<size; i++){
  13.         tmp = a[i]; /* a[i] is the element got from unsorted array */

  14.         j = i - 1; /* a[0] to a[i-1] is the sorted array */
  15.         while (j>=0 && a[j]>tmp){ /* while is more straightforward than for loop */
  16.             a[j+1] = a[j]; /* move the elment in sorted array */
  17.             j--;
  18.         }
  19.         /*
  20.         for (j=i-1; j>=0; j--){
  21.            if (a[j] > tmp){
  22.               a[j+1] = a[j];
  23.            } else {
  24.               break;
  25.            }
  26.         }
  27.         */
  28.         a[j+1] = tmp; /* j+1 is the place to insert element */
  29.     }
  30. }

阅读(1364) | 评论(0) | 转发(0) |
0

上一篇:1. Where to Start

下一篇:快速排序算法

给主人留下些什么吧!~~