zoukankan      html  css  js  c++  java
  • 希尔排序——Shell Sort

    前言:

    数据序列1: 13-17-20-42-28 利用插入排序,13-17-20-28-42. Number of swap:1;
    数据序列2: 13-17-20-42-14 利用插入排序,13-14-17-20-42. Number of swap:3;
    如果数据序列基本有序,使用插入排序会更加高效。

    基本思想:

    在要排序的一组数中,根据某一增量分为若干子序列,并对子序列分别进行插入排序。
    然后逐渐将增量减小,并重复上述过程。直至增量为1,此时数据序列基本有序,最后进行插入排序。

    过程:


    希尔排序

    平均时间复杂度:

    java代码实现:

    /**
     * 希尔(Shell)排序
     * 
     * @author Administrator
     *
     */
    public class ShellSort {
    
        /*
         * 数据序列1: 13-17-20-42-28 利用插入排序,13-17-20-28-42. Number of swap:1; 数据序列2:
         * 13-17-20-42-14 利用插入排序,13-14-17-20-42. Number of swap:3;
         * 如果数据序列基本有序,使用插入排序会更加高效。
         * 
         * 基本思想: 在要排序的一组数中,根据某一增量分为若干子序列,并对子序列分别进行插入排序。
         * 然后逐渐将增量减小,并重复上述过程。直至增量为1,此时数据序列基本有序,最后进行插入排序。
         */
        public static void main(String[] args) {
            // TODO Auto-generated method stub
            int[] arr = new int[] { 2, 3, 2, 5, 6, 1, -2, 3, 14, 12, 3, 8, 55, 44,
                    -10 };
            shellSort(arr);
            for (int i = 0; i < arr.length; i++) {
                System.out.print(arr[i] + "  ");
            }
        }
    
        private static void shellSort(int[] arr) {
            int incre = arr.length;
            while (incre > 0) {
                incre = incre / 2;
                for (int i = 0; i < incre; i++) {
                    for (int j = i + incre; j < arr.length; j += incre) {
                        for (int k = j; k > i; k -= incre) {
                            if (arr[k] < arr[k - incre]) {
                                int temp = arr[k];
                                arr[k] = arr[k - incre];
                                arr[k - incre] = temp;
                            } else {
                                break;
                            }
                        }
                    }
                }
            }
        }
    
    }
  • 相关阅读:
    Linux ls -l内容详解
    simple_strtoul
    proc_create的使用方法
    Ubuntu Linux 安装 .7z 解压和压缩文件
    3518调试2
    MTK camera 闪光灯Flashlight驱动调试流程
    samba访问其他服务器文件权限设置
    excel中单列相乘取整
    git fetch
    中文123456789
  • 原文地址:https://www.cnblogs.com/diyishijian/p/7775321.html
Copyright © 2011-2022 走看看