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

http://blog.csdn.net/pzhtpf/article/details/7559896

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

 

1,  直接插入排序

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

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

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

2)實例

(3)用java實現

  1.    package com.njue;  
  2.   
  3.    
  4.   
  5. publicclass insertSort {  
  6.   
  7. public insertSort(){  
  8.   
  9.      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};  
  10.   
  11.     int temp=0;  
  12.   
  13.     for(int i=1;i<a.length;i++){  
  14.   
  15.        int j=i-1;  
  16.   
  17.        temp=a[i];  
  18.   
  19.        for(;j>=0&&temp<a[j];j--){  
  20.   
  21.        a[j+1]=a[j];                       //將大於temp的值整體後移一個單位  
  22.   
  23.        }  
  24.   
  25.        a[j+1]=temp;  
  26.   
  27.     }  
  28.   
  29.     for(int i=0;i<a.length;i++)  
  30.   
  31.        System.out.println(a[i]);  
  32.   
  33. }  
  34.   
  35. }  
   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)基本思想:算法先將要排序的一組數按某個增量dn/2,n爲要排序數的個數)分成若干組,每組中記錄的下標相差d.對每組中全部元素進行直接插入排序,然後再用一個較小的增量(d/2)對它進行分組,在每組中再進行直接插入排序。當增量減到1時,進行直接插入排序後,排序完成。

2)實例:

(3)用java實現

  1. publicclass shellSort {  
  2.   
  3. publicshellSort(){  
  4.   
  5.     int a[]={1,54,6,3,78,34,12,45,56,100};  
  6.   
  7.     double d1=a.length;  
  8.   
  9.     int temp=0;  
  10.   
  11.     while(true){  
  12.   
  13.        d1= Math.ceil(d1/2);  
  14.   
  15.        int d=(int) d1;  
  16.   
  17.        for(int x=0;x<d;x++){  
  18.   
  19.            for(int i=x+d;i<a.length;i+=d){  
  20.   
  21.               int j=i-d;  
  22.   
  23.               temp=a[i];  
  24.   
  25.               for(;j>=0&&temp<a[j];j-=d){  
  26.   
  27.               a[j+d]=a[j];  
  28.   
  29.               }  
  30.   
  31.               a[j+d]=temp;  
  32.   
  33.            }  
  34.   
  35.        }  
  36.   
  37.        if(d==1)  
  38.   
  39.            break;  
  40.   
  41.     }  
  42.   
  43.     for(int i=0;i<a.length;i++)  
  44.   
  45.        System.out.println(a[i]);  
  46.   
  47. }  
  48.   
  49. }  
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章