我的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++)
由于shell
是int
但end
是int *
,因此它不知道如何进行比较。我该如何解决这个问题?
答案 0 :(得分:3)
假设这些是随机访问迭代器,因为否则性能会非常糟糕。
您可以使用std::distance
来获取两个迭代器之间的差异。您还可以使用std::advance
向迭代器添加整数。
答案 1 :(得分:1)
使用“迭代器”来寻址项目,并仅将整数用于相对偏移:
for (auto index = begin + shell; index < end; ++index) ...
顺便说一下,您可能需要shell < (end - begin)/3
,而不是(begin - end)
。