希尔排序是对于插入排序的一种优化
代码:
#include <stdio.h>
#include <stdlib.h>
void shell_sort(int* p, int len)
{
int i;
int j;
int step;
int tmp;
for (step = len / 2; step > 0; step = step / 2)
{
for (i = step; i < len; ++i)
{
if (p[i] < p[i - step])
{
tmp = p[i];
for (j = i - step; j >= 0 && tmp < p[j]; j = j - step)
{
p[j + step] = p[j];
}
p[j+step] = tmp;
}
}
}
for (i = 0; i < len; i++)
{
printf("%d ", p[i]);
}
}
int main()
{
int len;
scanf_s("%d", &len);
int *p = (int *)malloc(sizeof(int) * len);
if (p == NULL)
{
return 1;
}
else
{
for (int i = 0; i < len; i++)
{
scanf_s("%d", p + i);
}
shell_sort(p, len);
}
free(p);
return 0;
}
结果