直接插入的泛型算法实现,没有哨兵,直接通过下标进行边界控制。
#include <iostream>
#include <vector>
using namespace std;
template<typename Randomaccessiterator>
void InsertSort(Randomaccessiterator begin, Randomaccessiterator end)
{
for (auto i = begin+1; i != end; ++i)
{
for (auto j = i ; j != begin; --j)
{
if (*j < *(j - 1))
iter_swap(j, j - 1);
}
}
}
int main(int argv, char** argc)
{
int a[] = { 5, 2, 7, 0, 9, 4, 1, 3, 8, 6 };
vector<int> ivec;
for (int i = 0; i < 10; ++i)
ivec.push_back(a[i]);
cout << "数组排序前:";
for (int i = 0; i < 10; ++i)
cout << a[i] << " ";
cout << endl;
cout << "数组排序后:";
InsertSort(a, a + 10);
for (int i = 0; i < 10; ++i)
cout << a[i]<<" ";
cout << endl;
cout << "容器排序前:";
for (int i = 0; i < 10; ++i)
cout << ivec[i] << " ";
cout << endl;
cout << "容器排序后:";
InsertSort(ivec.begin(),ivec.end());
for (int i = 0; i < 10; ++i)
cout << ivec[i]<< " ";
cout << endl;
}
测试结果: