程式員必知的8大排序(一)——-直接插入排序,希爾排序(java實現)

來源:互聯網
上載者:User

前幾天,看到一篇前輩的博文“程式員必知的8大排序”,不禁的手癢起來,重新翻開嚴蔚敏老師的《資料結構》複習了一遍,然後一一的用java去實現,其中有不足之處,還望各位道友指正出來。

 

先來看看8種排序之間的關係:

 

1, 
直接插入排序

  
(1)基本思想:在要排序的一組數中,假設前面(n-1) [n>=2] 個數已經是排

好順序的,現在要把第n個數插到前面的有序數中,使得這n個數

也是排好順序的。如此反覆迴圈,直到全部排好順序。

(2)執行個體

(3)用java實現

   package com.njue; publicclass insertSort {public insertSort(){     int a[]={49,38,65,97,76,13,27,49,78,34,12,64,5,4,62,99,98,54,56,17,18,23,34,15,35,25,53,51};    int temp=0;    for(int i=1;i<a.length;i++){       int j=i-1;       temp=a[i];       for(;j>=0&&temp<a[j];j--){       a[j+1]=a[j];                       //將大於temp的值整體後移一個單位       }       a[j+1]=temp;    }    for(int i=0;i<a.length;i++)       System.out.println(a[i]);}}

 

2, 
希爾排序(最小增量排序)

(1)基本思想:演算法先將要排序的一組數按某個增量d(n/2,n為要排序數的個數)分成若干組,每組中記錄的下標相差d.對每組中全部元素進行直接插入排序,然後再用一個較小的增量(d/2)對它進行分組,在每組中再進行直接插入排序。當增量減到1時,進行直接插入排序後,排序完成。

(2)執行個體:

(3)用java實現

publicclass shellSort {publicshellSort(){    int a[]={1,54,6,3,78,34,12,45,56,100};    double d1=a.length;    int temp=0;    while(true){       d1= Math.ceil(d1/2);       int d=(int) d1;       for(int x=0;x<d;x++){           for(int i=x+d;i<a.length;i+=d){              int j=i-d;              temp=a[i];              for(;j>=0&&temp<a[j];j-=d){              a[j+d]=a[j];              }              a[j+d]=temp;           }       }       if(d==1)           break;    }    for(int i=0;i<a.length;i++)       System.out.println(a[i]);}}

接下一篇:程式員必知的8大排序(二)-------簡單選擇排序,堆排序(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.