算法与数据结构的复习——希尔排序

希尔排序是在插入排序的基础之上做的优化,它进行跨度的比较从而保证当跨度为1的时候特别小的数不会留在数列的后面导致多次移动元素。

希尔排序跨度计算——  h=h*3+1   初始值为1  最大跨度不大于数组的长度的h的最大值。

跨度的减少——   h =(h-1)/3 

希尔排序实现代码

/**
 * 
 */
package ch08;

import ch02.InsertSort;

/**
 * @author lixin
 * @date 2018年7月24日
 * @Description 希尔排序
 */
public class ShellSort {
	// 希尔排序
	public static void sort(long[] arr) {
		// 初始化跨度为1
		int h = 1;

		// 计算最大跨度
		// 3h+1<=arr.length ==> h<arr.length/3
		while (h < arr.length / 3) {
			h = 3 * h + 1;
		}

		while(h > 0) {
			//进行插入排序
			long tmp = 0;
			for(int i = h; i < arr.length; i++) {
				tmp = arr[i];
				int j = i;
				while(j > h - 1 && arr[j - h] >= tmp) {
					arr[j] = arr[j - h];
					j -= h;
				}
				arr[j] = tmp;
			}
			//减小间隔
			h = (h - 1) / 3;
		}
	}
	
	
	public static void main(String[] args) {
		long[] arr = new long[]{23,2,12};
		for(int i=0;i<arr.length;i++){
			System.out.print(arr[i]+" ");
		}
		System.out.println();
		ShellSort.sort(arr);
		for(int i=0;i<arr.length;i++){
			System.out.print(arr[i]+" ");
		}
	}
	
}

猜你喜欢

转载自blog.csdn.net/braveandbeauty/article/details/81205541