Data Structures and Algorithms-希尔排序(个人java实现)

package Sort;

public class ShellSort {
	//希尔排序
	
	public static int[] shellSort(int[] array){
		
		int n = array.length;
		//确定步长

		int h=1;
		while(3*h+1<n){
			h=3*h+1;
		}
		int counter=1;//第几次
		
		while(h>0){
			//注意,这里的范围是h而不是n
			for(int i=0;i<h;i++){
				shellSortEveryH(i,h,array);
			}
			h=(h-1)/3;
		    System.out.println("这是第"+counter+"轮希尔排序h为"+h);
		    display(array);
			counter++;
		}
		
		return array;
	}

	private static void display(int[] array) {
		for(int i=0;i<array.length;i++){
			System.out.print(array[i]+"  ");
		}
	    System.out.println();

	}

	private static void shellSortEveryH(int beginIndex, int h,int[] array) {
		int targerIndex = beginIndex + h; //target代表当前所要插入的元素,即我们将target放到一个合适的位置
		while(targerIndex<array.length){
			int temp = (int) array[targerIndex];
			int previousIndex = targerIndex - h; 
			while(previousIndex >=0 && (int)array[previousIndex] > temp){//满足这个条件的时候将temp和previous交换位置
				array[previousIndex+h] = array[previousIndex];
				previousIndex = previousIndex - h;
			}
			//经过以上的while循环,我们已经为target找到了合适的位置。
			array[previousIndex+h] = temp;
			targerIndex = targerIndex + h;//为下一个target元素找到合适的位置
		}
	}
	
	public static void main(String[] args) {
		int[] array = new int[]{456,784,49,2,37,46,123,53
				,126,465,656,7689,45,23,89,46,237};
		System.out.println("原始数组数据为");
		display(array);
		int[] result = ShellSort.shellSort(array);
		System.out.println("排序好的数组");
		display(result);

	}
	
}

以下是数据测试:

原始数组数据为
456  784  49  2  37  46  123  53  126  465  656  7689  45  23  89  46  237  
这是第1轮希尔排序h为4
23  89  46  2  37  46  123  53  126  465  656  7689  45  456  784  49  237  
这是第2轮希尔排序h为1
23  46  46  2  37  89  123  49  45  456  656  53  126  465  784  7689  237  
这是第3轮希尔排序h为0
2  23  37  45  46  46  49  53  89  123  126  237  456  465  656  784  7689  
排序好的数组
2  23  37  45  46  46  49  53  89  123  126  237  456  465  656  784  7689 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值