希尔排序
它是通过比较相距一定间隔的元素来工作的,各趟比较所用的的距离随着算法的进行而减小,直到只比较相邻元素的最后一趟排序为止。由于这个原因,希尔排序有时也叫做缩小增量排序。
希尔排序使用一个序列h1,h2,h3.....ht的增量序列,只要h1= 1,在使用所有增量序列hk的排序之后,所有相隔hk个元素都被排序了,此时称hk排序。
例子:
初始 81 94 11 96 12 35 17 95 28 58 41 75 15
在5-排序后 35 17 11 28 12 41 75 15 96 58 81 94 95
在3-排序后 28 12 11 35 15 41 58 17 94 75 81 96 95
在1-排序后 11 12 15 17 28 35 41 58 75 81 94 95 96
代码实现
root@ubuntu:~/DataStruct/day3$
root@ubuntu:~/DataStruct/day3$ ./shellsort
7 3 2 1 9 9 10 6 7 9
-------------------------------
selectSort : 0.000001s
1 2 3 6 7 7 9 9 9 10
root@ubuntu:~/DataStruct/day3$
root@ubuntu:~/DataStruct/day3$
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
void benchmak(const char *name, void (*func)(int *arry, int), int arry[], int n)
{
clock_t startTime = clock();
func(arry, n);
clock_t endTime = clock();
printf("%s : %lfs\n", name, (double)(endTime - startTime) / CLOCKS_PER_SEC);
}
int* generateRandomArray(int n, int rangL, int rangR)
{
int* array = malloc(n *sizeof(int));
if(array == NULL)
return NULL;
srand(time(NULL));
for(int i = 0; i < n; i++)
{
array[i] = rand() % (rangR - rangL + 1) + rangL;
}
return array;
}
void shellSort(int array[], int n)
{
int i, j, increament;
int tmp;
for(increament = n/2; increament > 0; increament /= 2) //1 控制增量序列
{
for(i = increament; i < n; i++) //2 对hk的增量序列进行排序
{
tmp = array[i];
for(j = i; j >= increament; j-= increament)
{
if(tmp < array[j - increament])
{
array[j] = array[j - increament];
}
else
{
break;
}
}
array[j] = tmp;
}
}
}
int main(int argc, char *argv[])
{
//int arry[10] = {10, 7, 8, 9, 6, 4, 2, 3, 1, 5};
int n = 10;
int* arry = generateRandomArray(n, 1, 10);
if(arry == NULL)
return 0;
for(int i = 0; i < n; i++)
{
printf("%d\t", arry[i]);
}
printf("\n-------------------------------\n");
//selectSort(arry, n);
benchmak("selectSort", shellSort, arry, n);
for(int i = 0; i < n; i++){
printf("%d\t", arry[i]);
}
printf("\n");
if(arry) free(arry);
return 0;
}
执行测试结果: