zoukankan      html  css  js  c++  java
  • 十大排序算法之(四)——插入排序

    #1,概念

    有一个已经有序的数据序列,要求在这个已经排好的数据序列中插入一个数,但要求插入后此数据序列仍然有序,这个时候就要用到一种新的排序方法——插入排序法,插入排序的基本操作就是将一个数据插入到已经排好序的有序数据中,从而得到一个新的、个数加一的有序数据,算法适用于少量数据的排序,时间复杂度为O(n^2)。是稳定的排序方法。插入算法把要排序的数组分成两部分:第一部分包含了这个数组的所有元素,但将最后一个元素除外(让数组多一个空间才有插入的位置),而第二部分就只包含这一个元素(即待插入元素)。在第一部分排序完成后,再将这个最后元素插入到已排好序的第一部分中。

    处理的思路简单清晰,我想结合vector和list来实现,对我现在而言,实现它不容易,在上班之余,花了两天时间调程序。

    #2,c++代码实现

     1 #include<iostream>
     2 #include<vector>
     3 #include<list>
     4 
     5 using namespace std;
     6 
     7 void InsertSort(vector<int >& src, list<int>& dst);
     8 void Insert(list<int>& dst,int val);
     9 void output(list<int> &src);
    10 
    11 int main(){
    12   vector<int > array = { 13, 19, 9, 5, 12, 8, 7, 4, 21, 2, 6, 11 };
    13   list<int > OutArray;
    14 
    15   InsertSort(array, OutArray);
    16   output(OutArray);
    17 
    18   system("Pause");
    19   return 0;
    20 }
    21 
    22 void InsertSort(vector<int >& src, list<int>& dst){
    23   size_t len=src.size();
    24 
    25   dst.push_back(src[0]);
    26 
    27   for(int i=1;i<len;i++){
    28   int val=src[i];
    29   Insert(dst,val);
    30   }
    31 }
    32 
    33 void Insert(list<int>& dst, int val){
    34   list<int>::iterator iter ;
    35   int numindex =1;
    36   for (iter = dst.begin(); iter != dst.end(); iter++, numindex++){
    37     if (dst.size() == 1){
    38       if (val < *iter)
    39         dst.insert(iter, val);
    40       else{
    41         dst.resize(dst.size() + 1);
    42         *(++iter) = val;
    43       }
    44     }
    45     else{
    46       if (val < *iter){
    47         dst.insert(iter, val);
    48         break;
    49       }
    50       else if (numindex==dst.size()){
    51         dst.resize(dst.size() + 1);
    52         *(++iter) = val;
    53       }
    54       else
    55         continue;
    56     }
    57   }
    58 }
    59 
    60 void output(list<int> &src){
    61   cout<<"The array after handling is: "<<endl;
    62   for(list<int>::iterator iter=src.begin();iter!=src.end();iter++)
    63     cout<<*iter<<"	";
    64   cout<<endl;
    65 }
    插入排序

    #3,程序运行结果

    我的十大排序算法,很多都只给了概念和代码,以后会慢慢加上代码的解释和算法!

  • 相关阅读:
    smarty相关
    Log4Net五步走[转载]
    The Water Horse: Legend of the Deep
    网站内容都是重复的,一个一个的复制真麻烦
    EXT2学习笔记,转载
    改写的一首诗赋
    CheckBoxList多选,获得选中的值!
    去年受朋友委托办了4张卡
    粒细胞
    GridView合并表头与行的反思
  • 原文地址:https://www.cnblogs.com/sophia-hxw/p/5670822.html
Copyright © 2011-2022 走看看