【代码积累】quick sort bia direction

public class Main {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		//int[] test = {5,4,3,2,1};
		int[] test={49,38,65,97,76,13,27,49,78,34,12,64,5,4,62,99,98,54,56,17,18,23,34,15,35,25,53,51};
		quickSortBia(test,0,test.length-1,false);
		
		showArray(test);
	}

	public static void showArray(int[] a) {
		for(int i=0;i<a.length;i++) {
			System.out.format("%d ", a[i]);
		}
		System.out.format("\r");
	}
	
	/*low and high are index of the elements in the array*/
	public static void quickSortBia(int[] a,int low,int high,boolean isAscend) {
		if( low >= high ) {
			return;
		}
		
		//calculate pivot index
		int pivotIndex = (low+high)/2;
		
		int storeIndex = partition(a,low,high,pivotIndex,isAscend);
		quickSortBia(a,low,storeIndex-1,isAscend);
		quickSortBia(a,storeIndex+1,high,isAscend);
	}
	
	public static int partition(int[] a,int low,int high,int pivotIndex,boolean isAscend) {
		int pivotValue = a[pivotIndex];
		int storeIndex = low; //This is the key step
		int tmp = 0;
		
		//swap a[pivotIndex] and a[high]
		a[pivotIndex] = a[high];
		a[high] = pivotValue;
		
		/*traverse from a[0] to a[high-1] in a loop,the storeIndex start from 0,and each time a[i] is smaller/larger than pivotValue 
		 * swap a[i] and a[storeIndex],increase storeIndex by 1,after the loop,swap a[high] and a[storeIndex],return storeIndex.*/
		for(int i=low;i<=high-1;i++) {
			if( true == isAscend ) {
				if(a[i] < pivotValue) {
					tmp = a[i];
					a[i] = a[storeIndex];
					a[storeIndex] = tmp;
					
					storeIndex++;  //increase after swap a[i] and a[storeIndex]
				}
			}
			else {
				if(a[i] > pivotValue) {
					tmp = a[i];
					a[i] = a[storeIndex];
					a[storeIndex] = tmp;
					
					storeIndex++;
				}
			}
		}
		
		tmp = a[storeIndex];
		a[storeIndex] = pivotValue;
		a[high] = tmp;
		
		showArray(a);
		
		return storeIndex;
	}
}

/*综述:
 * 快速排序的几个关键点:
 * 1、分治法,参照点的选取方式
 * 2、partition函数的作用是对根据pivot对数列进行趋势排列,然后根据pivot的最终index,将数列划分为2个子数列,再对子数列进行排序,递归调用
 *    partition的storeIndex的值取数列的首坐标,不能初始化为0
 *    partition中有3次swap
 *    只有在发生了a[i] 与 a[storeIndex]的交换后,才需要对storeIndex进行递增操作
 *    */

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值