演算法-java代碼實現希爾排序

來源:互聯網
上載者:User

標籤:main   1.2   turn   cal   直接插入   port   init   btn   ica   

 

希爾排序 第8節 希爾排序練習題 

對於一個int數組,請編寫一個希爾排序演算法,對數組元素排序。

給定一個int數組A及數組的大小n,請返回排序後的數組。保證元素小於等於2000。

測試範例:
[1,2,3,5,2,3],6
[1,2,2,3,3,5]
Java (javac 1.7)代碼自動補全     1
import java.util.*;
2
3
 
public class ShellSort {
4
    public int[] shellSort(int[] A, int n) {
5
        int i, step; //i標識每一組,step標識步長
6
        for(step = n / 2; step > 0; step /= 2){ //起始的步長為數組長度的一半
7
            for(i = step; i < n; i++){ //當前步長為step,開始插入排序
8
                if(A[i] < A[i-step]){ //每個元素與自己組內的資料進行直接插入排序 
9
                    int target = A[i];
10
                    int j = i; //j指示當前這一組遍曆到哪一個元素
11
                    while(j>0 && A[j-step] > target){
12
                        A[j] = A[j-step]; //將j-step位置上的元素移到位置j
13
                        j -= step;
14
                        if(j-step < 0)//如果j=1,step=3,沒有這個if的話,就會數組越界
15
                            break;
16
                    }
17
                    A[j] = target;
18
                }
19
            }
20
        }
21
        return A;
22
    }
23
}
  您的代碼已儲存
答案正確:恭喜!您提交的程式通過了所有的測試案例 

演算法-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.