排序系列 之 希爾排序演算法 —— Java實現

來源:互聯網
上載者:User

標籤:思路   res   java實現   param   組成   private   提高   shel   string   

 基本思想:

  希爾排序的實質就是分組插入排序,又稱縮小增量法。

  將整個無序序列分割成若干個子序列(由相隔某個“增量”的元素組成的)分別進行直接插入排序,然後依次縮減增量再進行排序,待整個序列中的元素基本有序時,再對全體元素進行一次直接插入排序。

  因為直接插入排序在元素基本有序的情況下,效率是很高的,因此希爾排序在時間效率上有很大提高。

 執行個體:

  無序序列:int a[] = {3,1,5,7,2,4,9,6};

  第一趟時: n=8; gap=n/2=4; 把整個序列共分成了4個子序列{3,2}、{1,4}、{5,9}、{7,6}

  第二趟時:gap=gap/2=2; 把整個序列共分成了2個子序列{2,5,3,9}、{1,6,4,7}

  第三趟時:對整個序列進行直接插入排序

  

  希爾排序是不穩定的

 

 Java實現:

package sort;/** * 希爾排序 演算法 的實現 * @author 那一季的銀杏葉 * */public class ShellSort {    public static void main(String[] args) {        // TODO Auto-generated method stub        new ShellSort().run();    }    private void run() {        // TODO Auto-generated method stub        int a[] = {3,1,5,7,2,4,9,6};        System.out.println("———————————————————希爾排序演算法—————————————————————");//        shellSort(a);        shellSort2(a);        printResult(a,a.length);    }    /**     * 希爾排序(縮小增量法) 屬於插入類排序       * 不穩定     * @param a     */    private void shellSort(int[] a){        int n=a.length;        int gap=n/2;        while(gap>=1){            for(int i=gap;i<a.length;i++){                int j=0;                int temp = a[i];                for(j=i-gap;j>=0 && temp<a[j];j=j-gap){                    a[j+gap] = a[j];                }                a[j+gap] = temp;            }            printResult(a,a.length);            gap = gap/2;        }    }    /**     * 嚴格按照定義來寫的希爾排序     * @param a     */    private void shellSort2(int[] a){        int n=a.length;                int i,j,k,gap;        for(gap=n/2;gap>0;gap/=2){            for(i=0;i<gap;i++){                        for(j=i+gap;j<n;j+=gap){                    int temp = a[j];                    for(k=j-gap;k>=0 && a[k]>temp;k-=gap){                        a[k+gap]=a[k];                    }                    a[k+gap]=temp;                }            }            printResult(a,a.length);        }    }    private void printResult(int[] a, int n){        for(int j=0;j<n;j++){            System.out.print(" "+a[j]);        }        System.out.println();    }}

 運行結果展示:

 

  (本文僅供學習交流,如有更好的思路,歡迎留下意見供大家探討學習~) 

 

排序系列 之 希爾排序演算法 —— 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.