日撸代码300行:第44天(希尔排序)

代码来自闵老师”日撸 Java 三百行(41-50天)“,链接:https://blog.csdn.net/minfanphd/article/details/116975863

	/**
	 * *****************************************************************
	 * Shell sort. We do not use sentries here because too many of them are needed.
	 * *****************************************************************
	 */
	public void shellSort() {
		DataNode tempNode;
		int[] tempJumpArray = { 5, 3, 1 };
		int tempJump;
		int p;
		
		for (int i = 0; i < tempJumpArray.length; i++) {
			tempJump = tempJumpArray[i];
			for (int j = 0; j < tempJump; j++) {
				
				for (int k = j + tempJump; k < data.length; k += tempJump) {
					tempNode = data[k];
					for (p = k - tempJump; p >= 0; p -= tempJump) {
						if (data[p].key > tempNode.key) {
							data[p + tempJump] = data[p];
						}else {
							break;
						}//of if
					}//of for p
					
					data[p + tempJump] = tempNode;
				}//of for k
			}//of for j
		}//of for i
		
	}//of shellSort
	
	/**
	 * ********************************************************
	 * Test the method.
	 * ********************************************************
	 */
	public static void shellSortTest() {
		int[] tempUnsortedKeys = { 5, 3, 6, 10, 7, 1, 9, 12, 8, 4 };
		String[] tempContents = { "if", "then", "else", "switch", "case", "for", "while", "throw", "until", "do" };
		DataArray tempDataArray = new DataArray(tempUnsortedKeys, tempContents);
		
		System.out.println(tempDataArray);
		tempDataArray.shellSort();
		System.out.println("Result\r\n" + tempDataArray);
		}//of shellSortTest

在这里插入图片描述
便于理解算法,附一张图,图片来自于博文:https://www.jianshu.com/p/d730ae586cf3
1、最不好理解的地方是data[p + tempJump] = data[p]和data[p + tempJump] = tempNode;第一句是将大的值往后移位置,每次移动的位置为tempjump。而只有if条件不成立的时候p的for循环会跳出,此时data[p].key是小于tempNode.key的。所以除了p的for循环,tempNode应该放在p的下一个加上tempJump的位置。
2、四个for循环,第一个控制循环的轮数;第二个for控制步长,tempJump每一组内的循环;第三个for循环保证每一轮j循环的时候,对比的是每一组的同一个位置的数据,这样就能将对应位置的数设置成一个插入排序;p的循环是为了查找该次循环的(插入排序)组内位置,跳出p的循环后,完成插入。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值