在shell排序中,建议使用3h+1
序列使用插入排序对列表进行h排序
//1, 4, 13, 40, ...
计算h
起始值的最佳公式是listsize
的三分之一,如下所示,
int h = 1;
while(h < listSize/3){ // why N/3?
h = 3*h + 1
}
while(h >= 1){
//h-sort the array
// perform insertionSort
h = h/3;
}
问题:
要执行shell排序,如何以数学方式证明h
(最大值)应小于listSize/3
?
答案 0 :(得分:3)
如果我们在条件h
之后继续增加(h < listSize/3)
,h
变得大于listSize
,并且在h排序中没有意义 - 我们无法比较项目{ {1}}和A[i]
因为第二个索引超出了列表范围。
答案 1 :(得分:0)
推荐用于 Shell 排序的最佳序列称为 Knuth Sequence,它实际上是 3h+1
,其中 h 从 0 开始,并由前一个方程的解代替。
h=0; 3*0+1=1
h=1; 3*1+1=4
h=4; 3*4+1=13
h=13; 3*13+1=40 and so on.
现在对于Shell排序,建议您在选择最佳“间隙”时按照反向 顺序的顺序进行。为此,您必须找到最后一个小于 listsize
的“差距”。
假设您的列表大小为 n=100,那么您希望间隔为 40,13,4,1
int gap;
for(int h=0; h<n; h=h*3+1)
gap=h;
这将使您达到 40。现在您进行插入排序,并且技术上将前一个间隙值设为 gap=gap/3
gap=(gap-1)/3
但由于剩余部分被丢弃,我们不担心。
所以你得到了类似的最终代码:
for(int h=0; h<n; h=h*3+1)
gap=h;
while(gap>=1)
{
//insertion sort with gap increments
gap=gap/3;
}