解法1 :
void ShellSort(int* arr, int size)
{
int gap = size;
while (gap > 1)
{
gap = gap 2; //调整希尔增量
int i = 0;
for (i = 0; i < size - gap; i++) //从0遍历到size-gap-1
{
int end = i; //end:需比较的位置
int temp = arr[end + gap]; //保存未排序过的某个值
while (end >= 0)
{
//在↓的情况下需要循环判断。end一直向前隔gap遍历,与新的数据即temp进行比较。如316
if (arr[end] > temp)
{
//end处插入更小的值temp,同时end向前,让temp与这小组里前面的值比较。
arr[end + gap] = arr[end];
end -= gap;
}
else
{
//如果136中的36都有序,加上前面的13已排过序,就都有序了。退出循环继续遍历i
break;
}
}
//把temp值还给最后位置
arr[end + gap] = temp; //以 end+gap 作为插入位置
}
}
}
如有错误欢迎大佬批评指正和交流~~