// 判断
int sort_judgeWithMode(int num1, int num2, int mode)
{
return mode? num1<num2:num1>num2;
}
// 希尔排序
void sort_shellSort(int *arr, int len, int mode)
{
int span=1, tmp;
do
{
span = span / 2;
span = span>0? span: 1;
for(int i = 0; i < span; i ++)
{
for(int j = i+span; j < len; j += span)
{
for(int k = j; k >= span; k -=span)
{
if(sort_judgeWithMode(arr[k], arr[k-span], mode))
{
tmp = arr[k-span];
arr[k-span] = arr[k];
arr[k] = tmp;
}
}
}
}
}while(span > 1);
}
运算结果
测试代码
#define N 10
int main()
{
int arr[N] = {1,3,543,234,65,23,4,23,234,87};
printf("\n降序排列结果:");
sort_shellSort(arr, N, 0);
for(int i = 0; i < N; i ++) printf("%3d ", arr[i]);
printf("\n\n升序排列结果:");
sort_shellSort(arr, N, 1);
for(int i = 0; i < N; i ++) printf("%3d ", arr[i]);
return 0;
}