Day 46 快速排序

46.1 平均时间复杂度为O(nlogn),但最坏情况还是O(n^2)。
46.2 Pivot 应该选 (该子序列的) 最后一个元素。
46.3 递归算法,每次只能确定 pivot 的位置。
46.4 判断条件 && (tempLeft < tempRight) 不能少。
46.5 (data[tempRight].key >= tempPivot) 不能写成 >,否则出现两个相同 key 时可能出错。

代码:

	/**
	 ******************************
	 * Quick sort recursively.
	 * 
	 * @param paraStart The start index.
	 * @param paraEnd   The end index.
	 ******************************
	 */
	public void quickSortRecursive(int paraStart, int paraEnd) {
		//Nothing to sort.
		if(paraStart >= paraEnd) {
			return;
		}//Of if
		
		int tempPivot = data[paraEnd].key;
		DataNode tempNodeForSwap;
		
		int tempLeft = paraStart;
		int tempRight = paraEnd-1;
		
		//Find the position for the pivot.
		//At the same time move smaller elements to the left and bigger one to the
		//right.
		while(true) {
			while((data[tempLeft].key<tempPivot) && (tempLeft<tempRight)) {
				tempLeft++;
			}//Of while
			
			while((data[tempRight].key >= tempPivot) && (tempLeft < tempRight)) {
				tempRight--;
			}//Of while
			
			if(tempLeft<tempRight) {
				//Swap.
				System.out.println("Swapping " + tempLeft + " and " + tempRight);
				tempNodeForSwap = data[tempLeft];
				data[tempLeft] = data[tempRight];
				data[tempRight] = tempNodeForSwap;
			}else {
				break;
			}//Of if
		}//Of while
		
		//Swap
		if(data[tempLeft].key > tempPivot) {
			tempNodeForSwap = data[paraEnd];
			data[paraEnd] = data[tempLeft];
			data[tempLeft] = tempNodeForSwap;
		}else {
			tempLeft++;
		}//Of if
		
		System.out.print("From " + paraStart + " to " + paraEnd + ": ");
		System.out.println(this);
		
		quickSortRecursive(paraStart, tempLeft - 1);
		quickSortRecursive(tempLeft + 1, paraEnd);
	}//Of quickSortRecursive

	/**
	 *****************
	 * Quick sort.
	 *****************
	 */
	public void quickSort() {
		quickSortRecursive(0, length - 1);
	}// Of quickSort

	/**
	 *****************
	 * Test the method.
	 *****************
	 */
	public static void quickSortTest() {
		int[] tempUnsortedKeys = { 1, 3, 12, 10, 5, 7, 9 };
		String[] tempContents = { "if", "then", "else", "switch", "case", "for", "while" };
		DataArray tempDataArray = new DataArray(tempUnsortedKeys, tempContents);

		System.out.println(tempDataArray);

		tempDataArray.quickSort();
		System.out.println("Result\r\n" + tempDataArray);
	}// Of quickSortTest

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值