N 元素个数
第一个for循环控制的是间隔
剩下的两个for循环用于直接插入排序
for (gap = N / 2; gap > 0; gap /= 2)
for (i = gap; i < N; i++)
for (j = i - gap; j >= 0 && A[j] > A[j + gap]; j -= gap)
{
temp=A[j];
A[j]=A[j+gap];
A[j+gap]=temp;
}
完整程序
#include <stdio.h>
#include<stdlib.h>
#include<math.h>
#define MAXN 10
typedef int ElementType;
void shellsort( ElementType A[], int N );
int main ()
{
ElementType A[MAXN];
int N, i;
scanf("%d", &N);
for ( i=0; i<N; i++ )
scanf("%d", &A[i]);
shellsort(A, N);
system("pause>nul");
return 0;
}
void shellsort( ElementType A[], int N )
{
int i, j, gap;
ElementType temp;
for (gap = N / 2; gap > 0; gap /= 2)
for (i = gap; i < N; i++)
for (j = i - gap; j >= 0 && A[j] > A[j + gap]; j -= gap)
{
temp=A[j];
A[j]=A[j+gap];
A[j+gap]=temp;
}
for ( i=0; i<N; i++ )
printf("%d
", A[i]);
}