69,373
社区成员
发帖
与我相关
我的任务
分享
/*希尔排序
*将算法 SellInsert 中所有的"dk"改为"1"即为算法 InsertSort,
*反过来说,算法 ShellInsert 可以看成是 InsertSort 的扩展。
*
*由于C语言的数组没有"负数"的下标,
*因此,在dk>1时需对j循环中以防"出界"另作"j>0"的判别,
*即L.r[0] 不再起到"监视哨"的作用,而仅仅作为一个暂存记录的空间。
*/
#include <iostream>
using std::cout;
using std::endl;
using std::string;
// 对顺序表L作一趟增量为dk的希尔排序
void ShellInsert(int *L, int dk){
for(int i=dk+1; i < 9; ++i ){
if( L[i] < L[i-dk] ){ // 将 L[i] 插入有序子表
L[0] = L[i];
L[i] = L[i-dk];
int j = i-2*dk;
for( ; j>0 && L[0] < L[j]; j-=dk ){
L[j+dk] = L[j];// 记录后移
}
L[j+dk] = L[0];// 插入到正确位置
}
}
} // ShellInsert
int main()
{
int li[9] = {2,1,8,5,9,4,7,3,6};//其中L[0]作为临时空间,只是比较L[1...8]
for(int i = 1; i<=9; i++){
cout << li[i-1] << " ";
}
cout << endl;
ShellInsert(li,5);
ShellInsert(li,3);
ShellInsert(li,1);
for(int i = 1; i<=9; i++){
cout << li[i-1] << " ";
}
cout << endl;
system("pause");
return 0;
}