插入排序

来源:互联网 发布:godaddy备案域名购买 编辑:程序博客网 时间:2024/05/21 22:10

一般来说,插入排序都采用in-place在数组上实现。具体算法描述如下:

  1. 从第一个元素开始,该元素可以认为已经被排序
  2. 取出下一个元素,在已经排序的元素序列中从后向前扫描
  3. 如果该元素(已排序)大于新元素,将该元素移到下一位置
  4. 重复步骤3,直到找到已排序的元素小于或者等于新元素的位置
  5. 将新元素插入到该位置中
  6. 重复步骤2

void insertion_sort(char array[],unsigned int first,unsigned int last)
{
int i,j;
int temp;
for (i = first+1; i<=last;i++)
{
temp = array[i];
j=i-1;

//与已排序的数逐一比较,大于temp时,该数移后
while((j>=first)&& (array[j]> temp))
{
array[j+1]= array[j];
j--;
                        array[j+1]= temp;//被排序数放到正确的位置
}

}
}

这个更好:

 void InsertSort(char array[],unsigned int n) {    int i,j;    int temp;    for(i=1;i<n;i++)    {      temp = array[i];//store the original sorted array in temp      for(j=i ; j>0 && temp < array[j-1] ; j--)//compare the new array with temp(maybe -1?)      {          array[j]=array[j-1];//all larger elements are moved one pot to the right          array[j-1]=temp;      }    } }

这个是c++语言版本的插入排序。为了支持list使用了std::advance()。

#include <iterator> template<typename biIter>void insertion_sort(biIter begin, biIter end)  {    typedef typename std::iterator_traits<biIter>::value_type value_type;    biIter bond = begin;    std::advance(bond, 1);    for(; bond!=end; std::advance(bond, 1)) {      value_type key = *bond;      biIter ins = bond;      biIter pre = ins;      std::advance(pre, -1);      while(ins!=begin && *pre>key) {        *ins = *pre;        std::advance(ins, -1);        std::advance(pre, -1);      }      *ins = key;    }  }
复杂度分析:
如果目标是把n个元素的序列升序排列,那么采用插入排序存在最好情况和最坏情况。最好情况就是,序列已经是升序排列了
,在这种情况下,需要进行的比较操作需(n-1)次即可。最坏情况就是,序列是降序排列,那么此时需要进行的比较共有n(n-1)/2次。
插入排序的赋值操作是比较操作的次数减去(n-1)次。平均来说插入排序算法复杂度为O(n2)
因而,插入排序不适合对于数据量比较大的排序应用。
但是,如果需要排序的数据量很小,例如,量级小于千,那么插入排序还是一个不错的选择。
原创粉丝点击