快速排序 递归

本文详细解析了快速排序算法的实现细节,特别强调了左右指针移动的正确顺序,并通过实例演示了正确的partition过程。

有生之年希望快速排序不要再写错了。。

注意一点,左右指针在往中间靠拢的时候,要先处理上边界。如果先处理下边界,那样的话是行不通的。举个例子就清楚些了。拿数组5,4,3,7,6,8 为例。例举了两个partition的过程。




代码:

package codes;

public class MyQuickSort {

	public static void main(String[] args) {
		int [] nums = {5,4,3,7,6,8};
		 new MyQuickSort().quickSort(nums, 0, nums.length-1);
        for( int i=0;i< nums.length;i++){
        	System.out.print(nums[i]+" ");
        }
	}
	public void quickSort(int [] nums, int low, int high){
		int q = partition(nums,low,high);
		//这里漏了,找了十分钟
		if( low < high){ 
		quickSort(nums,low,q-1);
		quickSort(nums,q+1,high);
		}
		
	}
	public int partition(int [] nums , int low , int high){
		int flag = nums[low];
		//int left = low,right = high;
		while(low<high){
                        //!!
			while( nums[high]>=flag && low<high ) high--;
			nums[low] =nums[high];
			while( nums[low]<=flag && low<high) low++;
			nums[high] =nums[low];
		}
		nums[low]=flag;
		return low;
		
	}

}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值