STL学習の挿入ソートのSTL実装


直接挿入ソートのC++実装およびランダム配列の生成方法これは以前の挿入ソートの例プログラムであり,STL実装に変更してもvectorの優位性はしばらく現れず,以下は挿入ソートのSTL実装である.
#include<iostream>
#include<cstring>
#include<cstdlib>
#include<time.h>
#include<cstdio>
#include<vector>
using namespace std;
//            
template <typename T>
void Random(vector<T> & a)
{
    int i=0;
    srand( (unsigned)time( NULL ) );
    while(i<a.size())
    {
        a[i++]=rand();
    }
}
template <typename T>
void InsertSort(vector<T> & a)
{
    int i, j;
    T temp;

    for (i= 1; i < a.size(); i++)
    {
        temp = a[i];//            ,           
        for (j = i-1; j >= 0 && temp < a[j]; j--)//a[j]           
        a[j+1] = a[j];//a[j]           
        //      ,a[j+1]  a[i]           ,      
         if(j!=(i-1)) /* i         ,       */
        {
            a[j+1]=temp;
        }
        /*      ,  temp >= a[j],      ,        
           a[j+2] = a[j+1],a[j+1]      , a[j]<=temp<a[j+1]
             ,a[j+1] = temp*/
    }
}
template <typename T>
void print(vector<T> & a)
{
    int i;
    for (i = 0; i < a.size(); i++)
        cout<<a[i]<<"  ";
}
int main()
{
    vector<int> a(30);
    Random(a);
    cout<<endl<<"--------------before sort----------------------"<<endl;
    print(a);
    InsertSort(a);
    cout<<endl<<"--------------after sort----------------------"<<endl;
    print(a);
    cout<<endl<<endl<<endl;
    return 0;
}
/********************

--------------before sort----------------------
15009  14379  25530  18743  8759  29948  13516  6320  24572  23136  16079  2395
 10781  20185  29451  6385  21180  14871  16450  18876  10062  30409  3381  1715
9  24385  5811  15465  21971  24034  11521
--------------after sort----------------------
2395  3381  5811  6320  6385  8759  10062  10781  11521  13516  14379  14871  15
009  15465  16079  16450  17159  18743  18876  20185  21180  21971  23136  24034
  24385  24572  25530  29451  29948  30409



Process returned 0 (0x0)   execution time : 0.513 s
Press any key to continue.

*********************/