5.插入排序——希爾插入排序

本文針對希爾插入排序。
時間複雜度是隨增量序列改變而改變的,希爾序列卻沒有最好的選擇。因此時間複雜度沒有確定。

思想是做幾次增量不爲1的插入排序,使得序列基本有序,最後再做一次增量爲1的插入排序。
增量序列選取的時候有一定原則,最後一個元素必須是1,而且所有的值沒有公因子。下邊給出大神們推薦的3個增量序列

 

程序:

#include <stdio.h>  
#include <stdlib.h>   
  
#define MAXSIZE 50   
#define N 15   
#define P 4   
  
typedef struct{  
    int key;  
    int other;  
}node;  
  
typedef struct  
{  
    node array[MAXSIZE + 1];  
    int length;  
}list;  
  
//做一次希爾排序   
void ShellInsert(list *l,int dk)  
{  
    int i,j;  
      
    for(i = dk + 1;i <= l->length;++i)  
        if(l->array[i].key < l->array[i-dk].key){  
            l->array[0] = l->array[i];  
            for(j = i - dk;j > 0 && l->array[0].key < l->array[j].key;j -= dk)  
                l->array[j + dk] = l->array[j];  
            l->array[j + dk] = l->array[0];  
        }  
}  
  
//希爾排序   
void ShellSort(list *l,int dlta[],int n)  
{  
    int i;  
    for(i = 0;i < n;++i)  
        ShellInsert(l,dlta[i]);  
}  

void print(list *l)  
{  
    int i;  
    for(i = 1;i <= l->length;i++)  
        printf("%d %d\t",l->array[i].key,l->array[i].other);  
    printf("\n");  
}  
  
   
void main()  
{  
    node data[N]={{5,6},{13,5},{22,2},{2,4},{6,5},{99,7},{6,15},{1,22},{15,12},{58,12},{48,40},{26,48},{38,35},{72,58},{61,22}};  
    list l;  
    int i,dt[P]={5,3,2,1};  //增量序列數組   
  
    for(i = 0;i < N;i++)  
        l.array[i + 1] = data[i];  
    l.length = N;  
      
    printf("befor sort:\n");  
    print(&l);  
      
    ShellSort(&l,dt,P);  
    printf("after shell sort:\n");  
    print(&l);  
} 


 

 

 

結果:

[09:57:38]# ./c
befor sort:
5 6     13 5    22 2    2 4     6 5     99 7    6 15    1 22    15 12   58 12   48 40   26 48   38 35   72 58   61 22
after shell sort:
1 22    2 4     5 6     6 15    6 5     13 5    15 12   22 2    26 48   38 35   48 40   58 12   61 22   72 58   99 7


 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章