首页 > 编程语言 > 详细

排序算法(四) 希尔排序

时间:2021-08-02 14:46:18      阅读:20      评论:0      收藏:0      [点我收藏+]

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 会导致想等元素的相对位置发生变化,所以是不稳定的。

排序算法(四) 希尔排序

原文:https://www.cnblogs.com/paidaxing7090/p/15089417.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!