希尔排序


希尔排序

        思路:希尔排序是基于插入排序,针对插入排序中 较小的值 很靠右时,交换次数很多的问题。通过 在元素之间增加间隔,先排序间隔项,最后在执行插入排序(实际上也就是间隔为1的排序)。

                    例如:增量间隔为4时, 先排序位置再 0、 4、8、12...的数,在排序 1、5、8、13的数,以此类推。结束以后,执行增量间隔为1的排序时,交换的位置最多为2.这样就大大减少了交换开销。

                    增量间隔的值 并不是固定的。一般来说 h = h*3 + 1  作为间隔序列。例如:对于1000个数据的数组来说,364、121、40、13、4、1。  增量间隔序列的值,就一个要求:最后一个值必然是1

        实现:

               

package com.test;

/**
 * 希尔排序
 * @author xurongsheng
 * @date 2017年4月12日 上午11:42:14
 *
 */
public class ShellSort {
	
	private long[] target;//待排序数据
	private int length;//数组项个数
	
	public ShellSort(){
		
	}
	
	public ShellSort(int maxLength){
		target = new long[maxLength];
		length = maxLength;
	}
	
	public void setTargetValue(int index,long value){
		target[index] = value;
	}
	
	public long getTargetValue(int index){
		return target[index];
	}
	
	public void display(){
		System.out.print("A=");
		for (int i = 0; i < length; i++) {
			System.out.print(target[i]+" ");
		}
		System.out.println(" ");
	}
	
	/**
	 * 希尔排序
	 * 时间复杂度: O(N(logN)²)~O(N²)
	 *          时间复杂度依赖于 增量间隔的值,一般为N^1.3
	 * @author xurongsheng
	 * @date 2017年4月12日 上午11:46:49
	 */
	public void shellSort(){
		
		//取最大增量间隔
		int h = 1; //间隔增量
		while(h <= length/3){
			h = h*3 + 1;
		}
		
		while(h>0){
			for (int i = h; i < length; i++) {
				long temp = target[i];
				int flag = i;
				while(flag > (h-1) && target[flag-h] >= temp){
					target[flag] = target[flag-h];
					flag -= h;
				}
				target[flag] = temp;
			}
			h = (h-1)/3; //递减增量间隔
		}
		
	}
	
	public static void main(String[] args) {
		int maxSize = 10000;
		ShellSort ss = new ShellSort(maxSize);
		
		for (int i = 0; i < maxSize; i++) {
			long n = (long) (Math.random()*1000);
			ss.setTargetValue(i,n);
		}
		ss.display();
		long startTime = System.currentTimeMillis();
		ss.shellSort();
		long endTime = System.currentTimeMillis();
		ss.display();
		System.out.println("耗时:"+(endTime - startTime)+"ms");
	}

}

        效率:希尔排序的时间复杂度,根据 增量间隔而不同。目前为止还没有定论,大于是在 O(N*(logN)²)  一般都表示为 N^1.3

                    所以,希尔排序在 最好情况下的时间复杂度为 O(N),最坏情况下的时间复杂度为O(N²),平均为N^1.3

        应用场景: 希尔排序对于几千个数据项的中等规模的数组排序表现良好。 其执行效率在最坏情况下和平均情况下的相差不多。所以很多排序优先会考虑希尔排序,效率不行再考虑其他排序。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值