插入排序的C++代码实现

本次实现的,是直接插入排序算法,暂时不做优化。

编译环境:C++11

代码实现如下:

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 _BothIter,
         typename _Compare = Comparator<decltype(*std::declval<_BothIter>())>>
void isort(_BothIter beg,
           _BothIter end,
           _Compare c = _Compare())
{
    _BothIter bound = beg;
    for(++bound; bound != end; ++bound)
    {
        auto temp(*bound);
        _BothIter it = bound;
        _BothIter v = it;
        while(v != beg)
        {
            if(c(temp, *--v) > 0)
            {
                *it = *v;
                it = v;
            }
            else
            { break; }
        }
        *it = temp;
    }
}

如有问题,欢迎指出!

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

猜你喜欢

转载自blog.csdn.net/qq811299838/article/details/104307557
今日推荐