希爾排序Linux下c 實現

     這次,我們談論下希爾排序,希爾排序也叫遞減增量排序算法。步長也是影響希爾排序的一個重要因素,我們這裏主要用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 


        希爾排序是個不穩定的排序,性能優於直接插入排序

發佈了248 篇原創文章 · 獲贊 141 · 訪問量 196萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章