标签:
插入排序是一种简单的排序算法,由于每一个嵌套循环都花费N次迭代,因此插入排序的时间复杂度为O(N^2)。
编码实现并测试:
#include <iostream>
#include <vector>
using namespace std;
template <typename Comparable>
void insertionSort( vector<Comparable> &a )
{
    int j;
    for ( int p = 1 ; p < a.size() ; p++ ){
        Comparable tmp = a[p];                          //保存当前元素值
        for ( j = p ; j > 0 && tmp < a[j - 1] ; j-- )   //通过循环将位置p之前比p大的元素都向右移一格
            a[j] = a[j - 1];
        a[j] = tmp;                                     //最后在适当的位置插入元素值.
    }
}
int main()
{
    cout << "请输入一些数据:" << endl;
    vector<int> vec;
    int temp;
    while ( cin >> temp )
        vec.push_back( temp );
    insertionSort( vec );
    cout << "按降序排列过的数据如下:" << endl;
    vector<int>::iterator iter = vec.begin();
    while( iter != vec.end() )
        cout << *iter++ << endl;
    return 0;
}
标签:
原文地址:http://www.cnblogs.com/ZRBYYXDM/p/5187045.html