排序算法之希爾排序【Java版】

引言

本篇是排序算法的第三篇,希爾排序,是插入排序的一個更高效的改進版。

1、算法步驟

1、對需要排序的數列,按照不同的步長進行分組;
2、對分組的數列進行組內排序;
3、然後繼續減小步長,重複1、2操作,當步長爲1的時候,排序就完成了。

下圖是網上找的,下面的d表示間隔,也叫做增量,相同顏色的是一組:
在這裏插入圖片描述

2、時間複雜度

平均時間複雜度O(n log n),最好情況O(n log2^2 n)

3、算法實現

public class ShellSort {

    public static void main(String[] args) {
        int[] numbers = {12,2,24,30,6,16};
        int[] result = ShellSort.sort(numbers);
        StringBuffer stringBuffer = new StringBuffer();
        for (int i = 0; i < result.length; i++) {
            stringBuffer.append(result[i] + " ");
        }
        System.out.println(stringBuffer.toString());
    }


    public static int[] sort(int[] numbers) {
        //對參數進行拷貝
        int[] needSort = Arrays.copyOf(numbers, numbers.length);

        int d = 1;
        while (d < needSort.length){
            //增量的計算公式
            d = d * 3 + 1;
        }
        while (d > 0) {
            for (int i = d; i < needSort.length; i++) {
                int tmp = needSort[i];
                int j = i - d;
                while (j >= 0 && needSort[j] > tmp) {
                    needSort[j + d] = needSort[j];
                    j -= d;
                }
                needSort[j + d] = tmp;
            }
            d = (int) Math.floor(d / 3);
        }
        return needSort;
    }
}

結束語

下一篇:將介紹排序算法之歸併排序。

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