查找与排序 希尔排序

简述

基本思想:希尔排序是把序列按下标的一定增量分组,对每组使用直接插入排序算法排序;随着增量的逐渐减少,每组包含的关键词越来越多,当增量减至1时,整个序列恰好被分为一组,算法便终止。

我们用几张图片来理解
在这里插入图片描述
在这里插入图片描述

在这里插入图片描述


实战代码

/**
	 *********************
	 * Shell sort. We do not use sentries here because too many of them are need.
	 *********************
	 */
	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 < length; k += tempJump) {
					tempNode = data[k];
					// Find the position to insert.
					// At the same time, move other nodes.
					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

					// Insert.
					data[p + tempJump] = tempNode;
				} // Of for k
			} // Of for j
			System.out.println("Round" + i);
			System.out.println(this);
		} // 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

运行结果

-------ShellSorTest-------
I am a data array with 10 items.
(5, if)  (3, then)  (6, else)  (10, switch)  (7, case)  (1, for)  (9, while)  (12, throw)  (8, until)  (4, do)  
Round0
I am a data array with 10 items.
(1, for)  (3, then)  (6, else)  (8, until)  (4, do)  (5, if)  (9, while)  (12, throw)  (10, switch)  (7, case)  
Round1
I am a data array with 10 items.
(1, for)  (3, then)  (5, if)  (7, case)  (4, do)  (6, else)  (8, until)  (12, throw)  (10, switch)  (9, while)  
Round2
I am a data array with 10 items.
(1, for)  (3, then)  (4, do)  (5, if)  (6, else)  (7, case)  (8, until)  (9, while)  (10, switch)  (12, throw)  
Result
I am a data array with 10 items.
(1, for)  (3, then)  (4, do)  (5, if)  (6, else)  (7, case)  (8, until)  (9, while)  (10, switch)  (12, throw)  


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值