希爾排序演算法

來源:互聯網
上載者:User

標籤:tiny   希爾排序   public   port   文檔   rand   desc   div   str   

import cn.idestiny.util.GeneratedArray;/** * @Auther: FAN * @Date: 2018/8/25 22:25 * @Description:希爾排序 * * 重點:設定增量 *   舉例來說,含有1000個資料項目的數組可能先以364為增量,然後以121為增量,以40為增量, *   以13為增量,以4為增量,最後以 1為增量進行希爾排序。用來形成間隔的數列被稱為間隔序列。 *   這裡所表示的間隔序列由Knuth提出,此序列是很常用的。 *   數列以逆向形式從1開始,通過遞迴運算式 h=3*b+1 來產生,初始值為1。 * * 當增量為arr.length/2的時候 * 1) 8,5,7,1,3,6,9.4  [8,3],[5,6]  [7,9],[1,4] * 2) 3,5,7,1,8,6,9,4  [3,7,8,9]  [5,1,6,4] * 3) 3,1,7,4,8,5,9,6  [3,1,7,4,8,5,9,6] * 4) 1,3,4,5,6,7,8,9 **/public class ShellSort {    public static void main(String[] args) {        int[] arr = GeneratedArray.randomGeneratedArray(10, 50, 100000);        long start = System.currentTimeMillis();        shellSort(arr);        GeneratedArray.isSorted(arr);        System.out.println(System.currentTimeMillis()-start);    }    public static void shellSort(int[] arr) {        //數組長度        int size = arr.length;        //設定間隔序列 詳細請看文檔注釋        int h = 1;        while(h<size/3){            h = 3*h +1;        }        //根據增量分組,增量為1時,只需要插入排序演算法微調即可        while(h>=1){            //對每個分組執行插入排序演算法            for(int i = h;i<size;i++){                //記錄插入值                int key = arr[h];                //插入值前一個元素的位置                int j = i-h;                //如果插入之比前一個值大,則插入之只需向後排列即可,不用在和前面的元素比較。                while(j>=0&&arr[j]>arr[j+h]){                    //如果插入值比它前面的值小,則大值(插入值前面的值)向後移動一位,                    arr[j+h] = arr[j];                    //插入值之前的角標                    j -= h;                }                //插入值最終應該放置的位置                arr[j+h] = key;            }            //縮小增量            h /= 3;        }    }}

 

希爾排序演算法

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.