实现基于迭代器的shell排序

时间:2013-09-06 20:37:33

标签: c++ iterator shellsort

我的shell排序如下:

template<class T>
void shellSort(T *begin, T *end) {
    int shell = 1;

    while (shell < (begin - end) / 3) shell = shell * 3 + 1;
    while (shell > 0) {
        for (auto index = shell; index < end; index++) {
            for (auto insertion = index; insertion >= shell && *(insertion - shell) > *(insertion); insertion -= shell) {
                swap(*(insertion - shell), *(insertion));
            }
        }

        shell = shell / 3;
    }
}

磨坊的漂亮运行。我遇到的问题就在这一行:

for (auto index = shell; index < end; index++)

由于shellintendint *,因此它不知道如何进行比较。我该如何解决这个问题?

2 个答案:

答案 0 :(得分:3)

假设这些是随机访问迭代器,因为否则性能会非常糟糕。

您可以使用std::distance来获取两个迭代器之间的差异。您还可以使用std::advance向迭代器添加整数。

答案 1 :(得分:1)

使用“迭代器”来寻址项目,并仅将整数用于相对偏移:

for (auto index = begin + shell; index < end; ++index) ...

顺便说一下,您可能需要shell < (end - begin)/3,而不是(begin - end)