这次,我们谈论下希尔排序,希尔排序也叫递减增量排序算法。步长也是影响希尔排序的一个重要因素,我们这里主要用Marcin Ciura设计的步长。关键代码如下:
1、希尔排序头文件:shellSort.h
#ifndef SHELLSORT_H #define SHELLSORT_H extern void shellSort(int * pArr, const int length); #endif
2、希尔排序源文件:shellSort.c
#include "shellSort.h" void shellSort(int * pArr, const int length) { const int pInc[9]={1,4,10,23,57,132,301,701,1750}; int len=sizeof(pInc)/sizeof(int); int i,k,j,tmp; int inc; k=0; while(*(pInc+k)<length && k<=len) { k++; } while(--k>=0) { inc=*(pInc+k); for(i=inc; i< length; i++) { tmp=*(pArr+i); j=i; while(j>=inc && *(pArr+j-inc)>tmp) { *(pArr+j)=*(pArr+j-inc); j=j-inc; } *(pArr+j)=tmp; } } }
3、main头文件:main.h
#ifndef MAIN_H #define MAIN_H #include<stdio.h> #include "shellSort.h" int main(void); void showArr(const int *pArr, const int length); void initRandomArr(int *pArr, const int length); #endif
4、main源文件:main.c
#include "main.h" int main(void) { printf("Input array length:\n"); int length; scanf("%d", &length); if(length<0) { printf("Array length must be larger 0\n"); return 1; } int arr[length]; initRandomArr(arr, length); printf("Get random array :\n"); showArr(arr, length); shellSort(arr, length); printf("shell sort result:\n"); showArr(arr, length); return 0; } void showArr(const int *pArr, const int length) { int i; for(i=0; i<length; i++) { printf("%d ", *(pArr+i)); } printf("\n"); } void initRandomArr(int *pArr, const int length) { int i; srand(time(NULL)); for(i=0; i< length; i++) { *(pArr+i)=rand()%1000; } }
5、编译:
[root@localhost shellSort]$ gcc -c shellSort.c [root@localhost shellSort]$ gcc -c main.c [root@localhost shellSort]$ gcc -o main main.o shellSort.o
执行可执行文件main如下:
[root@localhost shellSort]$ ./main Input array length: 12 Get random array : 518 713 265 31 350 931 592 872 489 927 640 106 shell sort result: 31 106 265 350 489 518 592 640 713 872 927 931
希尔排序是个不稳定的排序,性能优于直接插入排序