希爾排序

一、思想java

    能夠說是插入排序的變種, 採用插入排序的方法,先讓數組中任意間隔爲 h 的元素有序,剛開始 h 的大小能夠是 h = n / 2,接着讓 h = n / 4,讓 h 一直縮小,當 h = 1 時,也就是此時數組中任意間隔爲1的元素有序,此時的數組就是有序的了。shell

二、時間複雜度數組

    平均 O(n^1.25)spa

三、代碼實現code

public class ShellSort {
    public static void shellSort(int[] arr){
        if(arr == null || arr.length==0) return;
        int n = arr.length;
        //對每組間隔爲h的分組進行排序,剛開始h=n/2
        for(int h=n/2;h>0;h/=2){
            //對每一個局部分組進行插入排序
            for(int i=h; i<n;i++){
                //將arr[i]插入到所在分組的正確位置
                insertI(arr, h, i);
            }
        }
    }

    private static void insertI(int[] arr, int h, int i) {
        int temp = arr[i];
        int k;
        for(k = i-h; k>0 && temp < arr[k];k-=h){
            arr[k + h] = arr[k];
        }
        arr[k + h] = temp;
    }
}
相關文章
相關標籤/搜索
本站公眾號
   歡迎關注本站公眾號,獲取更多信息