JAVA資料結構--希爾排序

來源:互聯網
上載者:User

標籤:put   system   new   冒泡   com   string   rabl   public   super   

希爾排序通過將比較的全部元素分為幾個地區來提升插入排序的效能。這樣可以讓一個元素可以一次性地朝最終位置前進一大步。然後演算法再取越來越小的步長進行排序,演算法的最後一步就是普通的插入排序,但是到了這步,需排序的資料幾乎是已排好的了(此時插入排序較快)。

假設有一個很小的資料在一個已按升序排好序的數組的末端。如果用複雜度為O(n2)的排序(冒泡排序或插入排序),可能會進行n次的比較和交換才能將該資料移至正確位置。而希爾排序會用較大的步長移動資料,所以小資料只需進行少數比較和交換即可到正確位置。

 

  

 1 package DataStructures; 2  3 import java.util.Arrays; 4  5 public class ShellSort { 6     public static void main(String[] args) { 7         Integer nums[]=new Integer[]{45,1,22,15,6,3,7,5,14}; 8         shellsort(nums); 9         System.out.println("Last is: "+Arrays.toString(nums));10     }11     public static <AnyType extends Comparable<? super AnyType>>12     void shellsort(AnyType[] a){13         int j;14         for(int gap=a.length/2;gap>0;gap/=2){//確定增量,然後迴圈處理15             for(int i=gap;i<a.length;i++){16                 AnyType tmp=a[i];17                 for(j=i;j>=gap&&tmp.compareTo(a[j-gap])<0;j-=gap)//進行插入排序18                     a[j]=a[j-gap];19                 a[j]=tmp;20             }21             System.out.println("GAP="+gap+": "+Arrays.toString(a));22             23         }24     }25 }

 

output:

GAP=4: [6, 1, 7, 5, 14, 3, 22, 15, 45]GAP=2: [6, 1, 7, 3, 14, 5, 22, 15, 45]GAP=1: [1, 3, 5, 6, 7, 14, 15, 22, 45]Last is: [1, 3, 5, 6, 7, 14, 15, 22, 45]

 

當GAP=4時

0 1 2 3 4 5 6 7 8
45 1 22 15 6 3 7 5 14

 

 

第一趟:分為四組,增量為4,對應下標為 {0,4,8} {1,5} {2,6} {3,7}  然後各組內進行插入排序改變組內元素下標

當GAP=2時

0 1 2 3 4 5 6 7 8
6 1 7 5 14 3 22 15 45

 

 

 

第二趟:分為兩組,增量為2,對應下標 {0,2,4,6,8} {1,3,5,7},同樣進行插入排序

第三趟:同理

JAVA資料結構--希爾排序

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.