zoukankan      html  css  js  c++  java
  • 排序算法(四) 希尔排序

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

  • 相关阅读:
    【杭电】[4857]逃生
    【杭电】[2647]Reward
    【杭电】[1285]确定比赛名次
    【杭电】[1251]统计难题
    OJ系统上线——OJ.BoilTask.com
    【郑轻】[1893]985的数学难题
    【郑轻】[1900]985的“树”难题
    【郑轻】[1898]985的数字难题
    HDU 1850———nim博弈
    HDU 2188------巴什博弈
  • 原文地址:https://www.cnblogs.com/paidaxing7090/p/15089417.html
Copyright © 2011-2022 走看看