【代码积累】quick sort

import java.awt.image.PixelInterleavedSampleModel;


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};
		quickSort(test,0,test.length-1);
		
		for(int i=0;i<test.length;i++) {
			System.out.format("%d ", test[i]);
		}
		System.out.format("\r");
	}

	
	public static void quickSort(int[] a,int left,int right) {  //left,right是下标
		if( left >= right ) {
			return;
		}
		
		/*选出pivot的index作为参考,根据pivot对原数组进行划分,再分别对左右子数组递归调用quickSort*/
		//此处选择二分法选择pivot
		int pivotIndex = (left+right)/2;
		
		//调用partition,根据pivotValue对数组进行重排
		int regroupIndex = partition(a,left,right,pivotIndex);
		
//		for(int i=0;i<a.length;i++) {
//			System.out.format("%d ", a[i]);
//		}
//		System.out.format("\r");
		
		quickSort(a, left, regroupIndex-1);
		quickSort(a, regroupIndex+1, right);
	}
	
	public static int partition(int[] a,int left,int right,int pivotIndex) {
		int pivotValue = a[pivotIndex];
		int tmp = 0;  //用来swap
		
		//将pivotValue移动到数组尾
		tmp = pivotValue;
		a[pivotIndex] = a[right];
		a[right] = pivotValue;
				
		//逐个遍历 [left,right-1]的元素,将比pivotValue小的元素尽量往前放,同时storeIndex递增,最终storeIndex就是pivotValue该放的位置(storeIndex右边都是比pivotValue大的元素)
		int storeIndex = left;
		for(int i=left;i<=right-1;i++) {  //这里的left,right是实际的下标
			if( a[i] < pivotValue ) {
				//交换a[i]和a[storeIndex],storeIndex递增
				tmp = a[i];
				a[i] = a[storeIndex];
				a[storeIndex] = tmp;
				
				storeIndex++;
			}
		}
		
		//比较结束,比pivotValue小的元素都在 storeIndex的左边,大的元素在右边,交换a[storeIndex]与a[right]
		tmp = a[storeIndex];
		a[storeIndex] = a[right];
		a[right] = tmp;
		
		return storeIndex;
	}
}

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值