日撸代码300行学习笔记 Day 44

1.希尔排序

 该排序方法的基本思想是:先将整个待排元素序列分割成若干个子序列(由相隔某个“增量”的元素组成的)分别进行直接插入排序,然后依次缩减增量再进行排序,待整个序列中的元素基本有序(增量足够小)时,再对全体元素进行一次直接插入排序。因为直接插入排序在元素基本有序的情况下(接近最好情况),效率是很高的。

下面这张图一看就知道希尔排序思想是怎样的了吧。
 

2.代码

/**
	 * 
	 ***********************************
	 * @Title: shellSort
	 * @Description: Shell sort
	 * @param:
	 * @return: void
	 ***********************************
	 */
	public void shellSort() {
		DataNode tempNode;
		int[] tempJumpArray = { 4, 2, 1 };
		int tempJump;
		int p;
		for (int i = 0; i < tempJumpArray.length; i++) {
			//不同步进
			tempJump = tempJumpArray[i];
			for (int j = 0; j < tempJump; j++) {// 从0到尾
				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) {
						// data[p].key为前面的元素的值,tempNode为间隔后面的元素的值
						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

	/**
	 * 
	 ***********************************
	 * @Title: shellSortTest
	 * @Description: Test the method.
	 * @param:
	 * @return: void
	 ***********************************
	 */
	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

	/**
	 * 
	 ***********************************
	 * @Title: main
	 * @Description:
	 * @param: @param args
	 * @return: void
	 ***********************************
	 */
	public static void main(String args[]) {
		System.out.println("\r\n-------shellSortTest-------");
		shellSortTest();
	}// Of main

 3.总结

在希尔排序中,最好情况是步长为1的时候,并且整个序列几乎是有序的情况,这时时间复杂度为O(n)。在上面程序中,时间复杂度为。而希尔排序的时间复杂度是与步长序列有关的。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值