常用排序算法之希尔排序

希尔排序

    1、思想:希尔排序和直接插入排序很相似,希尔排序是在直接插入排序的基础上进行改进,将待排序列按增量d(一般d的初始值为d=array.length/2)分为诺干组,分别在每个组内进行直接插入排序,然后将增量d按照一定的规则减小(一般按照d=d/2的规则减小)。所以,这里我们可以参考以前的一篇文章“常用排序算法之直接插入排序”,希尔排序的代码也是在这篇文章代码之上修改而来的。
    2、希尔排序的过程这里引用一下赵坚、姜梅主编的《数据结构(C语言版)》第8章的【例8-3】,这本书是博主上大学时的教材,希尔排序在本书中写的很清晰,所以就引用一下,希望能够帮助大家理解。


    3、代码实现(java)
package sort.baohuajie;

import java.util.Arrays;
/**
 * @author 包华杰
 * 2017年12月3日
 * 
 * 这里使用两种方法实现。本人认为,第二种方法更能体现插入排序的思想。
 * 本代码是在直接插入排序的基础上修改而来的,可以参考以前的一篇博客
 */
public class ShellSort {

	public static void shellSort1(int[] array) {
		int temp;
		int d=array.length/2;
		int time=0;
		while(d>0){
			for (int i = d; i < array.length;) {
				for (int j = i; j > 0;) {
					if (array[j] < array[j - d]) {
						temp = array[j - d];
						array[j - d] = array[j];
						array[j] = temp;
					}
					j=j-d;
					time++;
					System.out.println("第" + time + "次排序结果:"+ Arrays.toString(array));
				}
				i=i+d;
				
			}
			d=d/2;
		}
	}
	public static void shellSort2(int[] array) {
		int temp=0;
		int j=0;
		int time=0;
		int d=array.length/2;
		while(d>0){
			for(int i=d;i<array.length;){
				temp=array[i];
				j=i-d;
				while(j>=0 && temp<array[j]){
					array[j+d]=array[j];
					j=j-d;
				}
				array[j+d]=temp;
				i=i+d;
				
			}
			d=d/2;
			time++;
			System.out.println("第" + time + "次排序结果:"
					+ Arrays.toString(array));
		}
	}
	public static void main(String[] args) {
		int[] array = { 58,46,71,95,84,25,37,58,63,12 };
		shellSort2(array);
	}
}


    4、执行结果
第1次排序结果:[25, 46, 71, 95, 84, 58, 37, 58, 63, 12]
第2次排序结果:[25, 46, 37, 95, 63, 58, 71, 58, 84, 12]
第3次排序结果:[12, 25, 37, 46, 58, 58, 63, 71, 84, 95]





  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值