3. 希爾算法

思想

希爾算法,是間隔對數組抽樣,從而形成多個子數組。在這多個子數組中,保證其排序正確性。

然後對抽樣間隔逐漸變小,再次保證其排序。

對於這些抽樣出來的子數組,應該如何排序呢?這裏用到插入排序。(選擇排序因爲需要每次遍歷,所以對於部分排序的數組,比較浪費時間)

希爾排序的間隔選取也是有講究的。

實現

import java.util.Arrays;

public class ShellSort {
    public static void main(String[] args) {
        int[] nums = {5, 12, 5, 7, 1, 4, 7, 8, 9};
        shellSort(nums);
        System.out.println(Arrays.toString(nums));
    }

    public static void shellSort(int[] nums){
        int len = nums.length;
        int h = 1;
        while(h<len/3) h = 3*h+1;
        while(h>=1){
            // 以h爲間隔分隔成多個子數組
            for (int i = h; i < len; i++) {
                for(int j = i; j >=h; j-=h){
                    if(nums[j]<nums[j-h]){
                        int temp = nums[j];
                        nums[j] = nums[j-h];
                        nums[j-h] = temp;
                    }
                }
            }
            h = h / 3;
        }
    }
}

複雜度

因爲希爾排序涉及到不同的h選取,所以複雜度研究比較複雜,故暫不做分析。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章