生活随笔
收集整理的這篇文章主要介紹了
希尔排序Linux下C实现
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
2019獨角獸企業重金招聘Python工程師標準>>>
本次,我們談論下希爾排序,希爾排序也叫遞減增量排序算法。步長也是影響希爾排序的一個重要因素,我們這里主要用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? ?希爾排序是個不穩定的排序,性能優于直接插入排序。
轉載于:https://my.oschina.net/fenglinwansu/blog/81637
總結
以上是生活随笔為你收集整理的希尔排序Linux下C实现的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。