// algINSERTIONSORT.cpp : 定義控制檯應用程序的入口點。
//
//算法導論 P17 2010.09.07 @lx
#include "stdafx.h"
#include <vector>
#include <iostream>
using namespace std;
template<class T>
inline void InsertionSort(vector<T>& A)
{
for(int j = 1; j < A.size(); j++)
{
T key = A[j];
//Insert A[j] into the sorted sequence A[1...j-1]
int i = j - 1;
while(i >= 0 && A[i] > key)
{
A[i + 1] = A[i];
i = i - 1;
A[i + 1] = key;
}
}
}
template <class T>
inline void PRINT_ELEMENTS(const T& col1, const char* optcstr = "")
{
typename T::const_iterator pos;
cout << optcstr;
for(pos = col1.begin(); pos != col1.end(); ++pos)
{
cout << *pos << ' ';
}
cout << endl;
}
int _tmain(int argc, _TCHAR* argv[])
{
vector<int> A;
A.push_back(3);
A.push_back(5);
A.push_back(1);
PRINT_ELEMENTS(A,"the older one is :");
InsertionSort(A);
PRINT_ELEMENTS(A,"the new one is :");
return 0;
}
插入排序
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.