zoukankan      html  css  js  c++  java
  • 算法导论:插入排序

     1 /*算法导论:P15 插入排序
    2 * 使用方法:vector<T> vec, InsertSort(vec)
    3 *
    4 */
    5 #include<vector>
    6 #include<iterator>
    7 using namespace std;
    8 template<typename T>
    9 void InsertSort(vector<T> &array)
    10 {
    11 //typename的作用是告诉c++编译器,typename后面的字符串为一个类型名称,而不是成员函数或者成员变量
    12 //定义两个Vector的迭代器
    13 typename vector<T>::iterator iter_temp1,iter_temp2;
    14 T key;//临时变量保存
    15 for(iter_temp1=array.begin()+1;iter_temp1!=array.end();iter_temp1++)
    16 {
    17 //先保存迭代数据
    18 key=*iter_temp1;
    19 for(iter_temp2=iter_temp1;iter_temp2 > array.begin() && key < *(iter_temp2-1);iter_temp2--)
    20 {
    21 //将比key大的数据向后移位,为key腾出位置
    22 *iter_temp2=*(iter_temp2-1);
    23 }
    24 //将key放到正确的排序位置
    25 *iter_temp2=key;
    26 }
    27 }
    28 #include<iostream>
    29 int main()
    30 {
    31 int a[12]={23,43,34,65,76,27,11,92,63,16,51,26};
    32 vector<int> array(a,a+12);
    33
    34 InsertSort(array);
    35 int i;
    36 for(i=0;i<12;i++)
    37 {
    38 cout<<array[i]<<' ';
    39 }
    40 cout<<endl;
    41 cin>>i;
    42 }
  • 相关阅读:
    公共服务领域英文译写规范
    [.NET Core]
    [WebAPI]
    [C#]
    [ES]
    [.Net Core]
    [SourceTree]
    如何使用一个库中不存在的函数
    在使用masm32 rc编译资源文件.rc出现的问题
    MSDN 2005 安装问题
  • 原文地址:https://www.cnblogs.com/shengansong/p/2299074.html
Copyright © 2011-2022 走看看