1. 程式人生 > 其它 >排序演算法(四) 希爾排序

排序演算法(四) 希爾排序

shellSort

1.動圖演示

2.程式碼實現

//測試工具類在這裡 https://www.cnblogs.com/paidaxing7090/p/15080493.html
import 測試工具類.SortTestHelper;


public class ShellSort {

    // 我們的演算法類不允許產生任何例項
    private ShellSort(){}

    public static void sort(Comparable[] arr){

        int n = arr.length;

        // 計算 increment sequence: 1, 4, 13, 40, 121, 364, 1093...
        int h = 1;
       
        while (h < n/3) h = 3*h + 1;

        while (h >= 1) {

            // h-sort the array
            for (int i = h; i < n; i++) {

                Comparable e = arr[i];
                int j = i;
                for ( ; j >= h && e.compareTo(arr[j-h]) < 0 ; j -= h)
                    arr[j] = arr[j-h];
                arr[j] = e;

               /* for (int k =0;k<arr.length;k++)
                {  System.out.print(arr[k] + " ");
                    if (k==arr.length - 1){System.out.println();}
                }*/
            }

            h /= 3;
        }
    }
    public static void main(String[] args) {

        int N = 100000;
        Integer[] arr = SortTestHelper.generateRandomArray(N, 0, 10000);
        Integer[] clone = arr.clone();
        SortTestHelper.testSort("sort.InsertionSort2", clone);
        SortTestHelper.testSort("sort.ShellSort", arr);

        return;
    }
    

}

3.測試結果

可以看到shellSort 比直接插入排序效率要高很多。

4.演算法分析

4.1描述

希爾排序的基本思想是:先將整個待排序的記錄序列分割成為若干子序列分別進行直接插入排序,待整個序列中的記錄"基本有序"時,再對全體記錄進行依次直接插入排序。

4.2分析


shellSort 會導致想等元素的相對位置發生變化,所以是不穩定的。

有疑問,可以留言。