1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
| #include <stdio.h>
#define ARRSIZE(arr) (sizeof(arr) / sizeof(arr[0]))
void ShellSort(int elements[], int length)
{
int gap; //增量
for (gap = length / 2; gap > 0; gap /= 2)
{
for (int i = gap; i < length; i++)
{
int tmp = elements[i];
int j;
//这里类似于插入排序,只是把增量1变成了gap
for (j = i; j > 0; j -= gap)
{
if (elements[j - gap] > tmp)
{
elements[j] = elements[j - gap];
}
else
break;
}
elements[j] = tmp;
}
}
}
int main(int argc, char const *argv[])
{
int elems[] = {3, 4, 2, 1, 5, 9, 2, 1, 0, 22, 33, 5, 112, 11, 22, 55, 22, 61, 97};
int len = ARRSIZE(elems);
ShellSort(elems, len);
for (int i = 0; i < len; i++)
printf("%4d", elems[i]);
printf("\n");
return 0;
}
|