錯誤代碼
void insert1(int a[],int n)
{
int i,j,k;
int temp;
for (k = 2;k >= 1;k /= 2)
{
for (i = k;i < n;i++)
{
temp = a[i];
for (j = i - k ;j >= 0 && a[j] > a[i];j = j - k)
{
a[j+1] = a[j];
}
a[j+1] = temp;
}
}
return;
}
錯誤原因:1,k初始值應該爲數組長度的一半,每次除以2.
2,希爾排序是相鄰k個大小的元素看作一個有序隊列,所以下面的j + 1都要換成j + k;
正確代碼
void insert1(int a[],int n)
{
int i,j,k;
int temp;
for (k = n/2;k > 0;k = k/2)
{
for (i = k;i < n;i++)
{
temp = a[i];
for (j = i - k;(j >= 0 && a[j] >= temp);j = j - k)
{
a[j+k] = a[j];
}
a[j+k] = temp;
}
}
return;
}