希尔排序的C++代码实现

编译环境:C++11

代码实现如下:

#include <cmath> // std::log2  std::pow
#include <type_traits> // std::declval

typedef unsigned long size_type;

template<typename _Tp>
constexpr size_type distance(const _Tp &_1, const _Tp &_2)
{ return _1 < _2 ? _2 - _1 : _1 - _2; }

template<typename _Tp>
struct Comparator
{
    int operator()(const _Tp &arg1, const _Tp &arg2) const
    {
        if(arg1 < arg2) return 1;
        if(arg2 < arg1) return -1;
        return 0;
    }
};

/* 希尔排序
 * [@beg, @end)  待排序的范围,存放排序结果,须支持随机迭代
 */
template<typename _RandomIter,
         typename _Compare = Comparator<decltype(*std::declval<_RandomIter>())>>
void ssort(_RandomIter beg,
           _RandomIter end,
           _Compare c = _Compare())
{
    size_type total_size = distance(beg, end);
    if(total_size <= 1) 
    { return; }
    size_type fin = static_cast<size_type>(std::log2(total_size - 1));
    size_type _1 = static_cast<size_type>(std::pow(2, fin));
    size_type dist = _1 - 1;
    size_type i, j;
    while(dist > 0)
    {
        for(i = dist; i < total_size; ++i)
        {
            auto temp = *(beg + i);
            for(j = i; j >= dist; j -= dist)
            {
                if(c(temp, *(beg + j - dist)) > 0)
                { *(beg + j) = *(beg + j - dist); }
                else 
                { break; }
            }
            *(beg + j) = temp;
        }
        if(dist == 1)
        { break; }
        _1 /= 2;
        dist = _1 - 1;
    }
}

如有问题,欢迎指出!

发布了19 篇原创文章 · 获赞 1 · 访问量 2768

猜你喜欢

转载自blog.csdn.net/qq811299838/article/details/104307923