我发现两个接近的序列在shellsort上的比较数量大不相同。
第一个序列是斐波那契序列。
F(0)= 1,F(1)= 2
F(n)= F(n-1)+ F(n-2),n> 1
第二个顺序是
G(0)= 1
G(n)= F(n + 2)+(-1)^ n,n> 0
为什么第二个序列在shellsort上的比较次数比第一个序列少?
我写了一个基准来记录不同种类的排序算法的平均比较数和相对偏差。测试案例包括随机案例,有序案例和逆序案例。 另外,我添加了std :: sort和std :: sort_heap来提供基准的基准。
template<class Iterator, class Compare, class T, T ...Seq>
constexpr void sort_impl(Iterator first, Iterator last, Compare comp, const T size, std::integer_sequence<T, Seq...>) noexcept {
for (const auto gap : {Seq...}) {
if (size > gap) {
const auto h = first + gap;
for (auto i = h; i < last; i++) {
if (comp(*i, *(i - gap))) {
auto v = std::move(*i);
auto j = i;
do {
*j = std::move(*(j - gap));
j -= gap;
} while (j >= h && comp(v, *(j - gap)));
*j = std::move(v);
}
}
}
}
}
random integer array
fib shell sort cmp: 1325095023.99 (± 3.73%)
fib fuzzy shell sort cmp: 572594719.24 (± 1.40%)
std sort cmp: 281854794.48 (± 1.17%)
std sort heap cmp: 236300381.92 (± 0.00%)
ascend integer array
fib shell sort cmp: 315842185.00 (± 0.00%)
fib fuzzy shell sort cmp: 295842191.00 (± 0.00%)
std sort cmp: 316531837.00 (± 0.00%)
std sort heap cmp: 238288048.00 (± 0.00%)
descend integer array
fib shell sort cmp: 353359827.00 (± 0.00%)
fib fuzzy shell sort cmp: 339869035.00 (± 0.00%)
std sort cmp: 222097162.00 (± 0.00%)
std sort heap cmp: 240430389.00 (± 0.00%)