http://www.360doc.com/content/19/1206/09/67764432_877779584.shtml
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
#define LEN 10
typedef int dataType;
//初始化數(shù)組,賦值整數(shù)隨機(jī)數(shù)
void initArr(dataType arr[], int len);
//希爾排序
void shellSort(dataType arr[], int len);
//交換兩個數(shù)
void swap(dataType &x,dataType &y);
//打印數(shù)組元素
void print(dataType arr[], int len);
int main()
{
dataType arr[LEN];
initArr(arr,LEN);
printf("================希爾排序================");
//輸出排序前的數(shù)組元素
printf("\n排序前數(shù)組元素:");
print(arr,LEN);
shellSort(arr,LEN);
printf("\n排序后數(shù)組元素:");
print(arr,LEN);
printf("\n");
return 0;
}
//初始化數(shù)組伐厌,賦值整數(shù)隨機(jī)數(shù)
void initArr(dataType arr[], int len)
{
int i = 0;
srand((unsigned)time(NULL));
for(i = 0; i < len; i++)
arr[i] = rand();
}
//希爾排序
void shellSort(dataType arr[], int len)
{
int h = 0;
int i = 0;
int j = 0;
//設(shè)置步長
for(h = 1; h < len; h = 3 * h + 1)
;
while(h)
{
h /= 3;
if(h < 1)
? break;
for(i = h; i < len; i++)
? for(j = i; j >= h; j-=h)
? {
? if(arr[j-h] < arr[j])
? break;
? swap(arr[j-h],arr[j]);
? }
}
}
//交換兩個數(shù)
void swap(dataType &x,dataType &y)
{
dataType temp;
temp = x;
x = y;
y = temp;
}
//打印數(shù)組元素
void print(dataType arr[], int len)
{
int i = 0;
for(i = 0; i< LEN; i++)
{
if(i % 5 == 0)
{
? printf("\n");
}
printf("%d\t",arr[i]);
}
}