經典排序——希爾排序

  感謝太原理工大學的算法演示:http://www.tyut.edu.cn/kecheng1/site01/suanfayanshi/shell_sort.asp算法

 

在希爾排序中主要是要明白在最底層是經過一次又一次的插入排序來實現的。每次都當作是h(k)個獨立的數組,進行插入排序,而後循環h(k-1),h(k-2).....h(1);shell

代碼以下:若是gap=1;那就是最後的插入排序了,不明白插入排序能夠看個人插入排序數組

  

 1 public static void Shell(int [] test){
 2     int len = test.length;
 3     int temp,j;
 4     for(int gap=len/2;gap>0;gap=gap/2){
 5         for(int i=gap;i<len;i++){
 6             if(test[i-gap]>test[i]){//關鍵在於這裏的控制test[i]
 7             temp = test[i];
 8         for(j=i;j>=gap&&temp<test[j-gap];j=j-gap){
 9               test[j]=test[j-gap];
10         }
11         test[j]=temp;
12             }
13     }
14             }
15 }
相關文章
相關標籤/搜索