首页 > 编程语言 > 详细

插入排序Insertion sort

时间:2016-03-18 17:42:11      阅读:139      评论:0      收藏:0      [点我收藏+]

插入排序就是每一步都将一个待排数据按其大小插入到已经排序的数据中的适当位置,直到全部插入完毕。

插入排序方法分直接插入排序和折半插入排序两种,这里只介绍直接插入排序。

#include <iostream>
using namespace std;
static void insert_sort(int unsorted[], int length)
{
  for(int i=1; i<length; i++)
  {   
    int key = unsorted[i];
    int j = i - 1;
    while(j >= 0 && unsorted[j] > key)
    {
      unsorted[j+1] = unsorted[j];
      j=j-1;
    }
    unsorted[j+1] = key;
  }  
}

int main(void)
{
  int x[6] = {5,2,4,6,1,3};
  insert_sort(x, 6);
  for(int i=0; i<6; i++)
  {
    cout << x[i] << " ";
  }
  cout << endl;
  getchar();
  return 0;
}

  

插入排序Insertion sort

原文:http://www.cnblogs.com/bwin/p/5292738.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!