实现基于迭代器的 shell 排序

Implementing a iterator based shell sort

本文关键字:shell 排序 迭代器 实现      更新时间:2023-10-16

我的外壳排序如下所示:

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++)

由于shell是一个intend是一个int *它不知道如何进行比较。我该如何解决这个问题?

假设这些是随机访问迭代器,否则性能会很差。

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

使用"迭代器"对项目进行寻址,仅对相对偏移量使用整数:

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

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