近来在学习<<STL源码剖析>>和C++11,按自己的理解自己动手实现排序算法的实现,代码中多用C++11的新特性。
这算是自娱自乐吧
这里只考虑排序的对象的有move构造函数,move赋值函数。
#ifndef YYRSort_H_
#define YYRSort_H_
#include <algorithm>
using namespace std;
const size_t Threshold = 16;
namespace YYRSort
{
//插入排序
template<typename RandomIterator>
inline void InsertionSort(RandomIterator first, RandomIterator last)
{
if((last-first) < 2) //It don't need to sort when the container only has one or zero element.
{
return;
};
auto Index = first + 1;
decltype(Index) NextPos;
decltype(Index) PrePos;
auto TempValue = *Index;
for(;Index != last; ++Index)
{
NextPos = Index - 1;
PrePos = Index;
TempValue = std::move(*Index);
if(TempValue < *first)
{
std::move_backward(first, Index, Index+1);
*first = std::move(TempValue);
}
else
{
while(true)
{
if(TempValue < *NextPos)
{
*PrePos = std::move(*NextPos);
PrePos = NextPos;
--NextPos;
}
else
{
*PrePos = std::move(TempValue);
break;
}
}
}
}
}
//生成最大堆