2個java希爾排序樣本_java

來源:互聯網
上載者:User

java希爾排序

希爾排序是插入排序的一種類型,也可以用一個形象的叫法縮小增量法。基本思想就是把一個數組分為好幾個數組,有點像分治法,不過這裡的劃分是用一個常量d來控制。

這個0<d<n,n為數組的長度。這個演算法有了插入排序的速度,也可以算是一個改進演算法,在插入演算法中,如果有一個最小的數在數組的最後面,用插入演算法就會重最後一個

位置移動到第一個,這樣就會浪費很大,使用這個改進的希爾排序可以實現資料元素的大跨度的移動。也就是這個演算法的優越之處。

複製代碼 代碼如下:

package cn.cqu.coce.xutao;

public class shell3 {
 public static void main(String args[]){
  int a[]={7,43,23,5,3,2,0,6,74,9};
  int n=a.length;
  for(int i=0;i<n;i++)
   System.out.print(a[i]+"\t");
  System.out.println();
     for(int gap=n/2;gap>0;gap/=2){
      for(int i=gap;i<n;i++){
       for(int j=i-gap;j>=0&&a[j]>a[j+gap];j-=gap){
        int temp=a[j+gap];
        a[j+gap]=a[j];
        a[j]=temp;
       }
      }
     }
  for(int i=0;i<n;i++)
   System.out.print(a[i]+"\t");
  System.out.println();
 }
}



第二個樣本

複製代碼 代碼如下:

class Shell
{
    public void shell_sort(int [] arrays){
        for(int d=5;d>0;d=d-2){
            for(int c=0;c<arrays.length-d;c++){
                for(int i=c;i<arrays.length;i=i+d){
                    for(int j=i;j>0;j=j-d){
                        if(j<d)
                            break;
                        if(arrays[j]<arrays[j-d]){
                            int tmp;
                            tmp=arrays[j];
                            arrays[j]=arrays[j-d];
                            arrays[j-d]=tmp;

                        }
                    }
                }

            }
            snp(arrays);
        }

    }
    public void snp(int[] arrays){
        for(int i=0;i<arrays.length;i++){
            System.out.print(arrays[i]+" ");

        }
        System.out.println();
    }
    public static void main(String[] args)
    {
        Shell s=new Shell();
        int[] a={45,20,80,40,26,58,66,70};
        s.shell_sort(a);

    }
}

運行結果:

複製代碼 代碼如下:

---------- java ----------
20 70 40 26 58 66 80
20 58 45 26 70 66 80
26 40 45 58 66 70 80

輸出完成 (耗時 0 秒) - 正常終止

聯繫我們

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