数据结构复习之–“Shell排序”-JAVA实现

Shell排序(Shell’ Sort),是对简单的插入排序的改进,改进的思路是,由于插入排序在数据基本有序时,其时间复杂度较小,特别的当数据有序时其时间复杂度为O(n),故如果我们可以将一个待排序的数据在排序前能够做到基本有序,那么利用插入排序是个非常好的选择,这也就是Shell排序的思想。

Shell排序的基本做法是,首先以一定的大间隔对数据进行排序,然后间隔不断缩小,继续进行排序,那么待排序的数据,就会逐渐变得基本有序,最后在用简单的插入排序,即间隔为1,因此希尔排序也被称为缩小增量排序(Dimininshing Increment Sort)
如对 5 6 8 7 1 3 15进行排序
间隔为3时
5 6 8 7 1 3 15 ===> 5 1 8 7 6 3 15 ===>5 1 3 7 6 8 15
间隔为2时
5 1 3 7 6 8 15 ===> 3 1 5 7 6 8 15 ===> 3 1 5 7 6 8 15
间隔为1时
3 1 5 7 6 8 15 ===>1 3 5 7 6 8 15 ===>1 3 5 7 6 8 15===>1 3 5 7 6 8 15===>1 3 5 6 7 8 15
===>1 3 5 6 7 8 15===>1 3 5 6 7 8 15

import java.util.Scanner;
public class ShellSortTest {
    /**
     * funcation:以传入的增量为间隔,进行一次插入排序
     * @param array 待排序数组,其中数组的第一个元素array[0],不存实际的数据,用做辅助空间
     * @param increment 增量间隔
     */
    private static void shellInsert(int[] array, int increment) {
        for (int i = increment + 1; i < array.length; i++) {
            if (array[i] < array[i - increment]) {
                array[0] = array[i];        //array中array[0]作为临时存储单元
                int j;
                //以增量为间隔,向前寻找比当前数据大的
                for (j = i - increment; j > 0 && array[0] < array[j]; j -= increment) {
                    array[j + increment] = array[j];//若找到的数据比当前待比较的数据大则以增量为间隔,向后移动
                }
                array[j + increment] = array[0];//将当前数据,插入到找到的位置中
            }
        }
    }

    /**
     * function:Shell插入排序,也叫缩小增量排序
     * @param array 待排序数组
     * @param icAry 增量数组,其中最后一个元素必须为1,也即最后一个增量必须为1
     */
    public static void shellSort(int[] array,int[] icAry){
        for (int i = 0; i < icAry.length; i++) {
            shellInsert(array,icAry[i]);
        }
    }

    /**
     * function:输入数组ary[1...end]中的数据
     * @param ary 待输出数组
     */
    private static void show(int[] ary){
        for (int i = 1; i < ary.length; i++) {
            System.out.print(ary[i]+" ");
        }
    }
    private static int[] getData(){
        Scanner sc = new Scanner(System.in);
        System.out.println("请输入待排序数据总个数:");
        int totalNums =  sc.nextInt();
        int[] inputData =  new int[totalNums+1];
        System.out.print("请输入待排序数据,以空格作为分隔符:");
        for (int i = 1; i < inputData.length; i++) {
            inputData[i]=sc.nextInt();
        }
        return inputData;
    }
    public static void main(String [] args){

        int[] inputData=ShellSortTest.getData();//获取待排序数据
        int[] increment={5,4,2,1};//自定义的增量数组
        ShellSortTest.shellSort(inputData, increment);//Shell插入排序
        ShellSortTest.show(inputData);//显示排序后的结果
    }
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值