快速排序

package hello;

import java.util.Stack;

/**非递归快速排序
 * @author zhangshancheng
 */
public class QuickStart {
	public static void main(String[] args) {
		int[] arr = {5,8,3,9,1,1,2,7,4,6,6};
		quickSort(arr);
		for(int i:arr)
			System.out.print(i+" ");
	}
	public static void quickSort(int[] arr){
		Stack<Left_Right> stack = new Stack<Left_Right>();
		stack.push(new Left_Right(0, arr.length-1));
		while(!stack.isEmpty()){
			Left_Right pop = stack.pop();
			int half = toHalf(arr, pop.left, pop.right);
			if((half+1)<pop.right)
				stack.push(new Left_Right(half+1, pop.right));
			if((half-1)>pop.left)
				stack.push(new Left_Right(pop.left,(half-1)));
		}
	}
	public static int toHalf(int[] arr,int left,int right){
		int pivot = arr[right];//得到枢轴
		
		while (left<right) {
			//左边开始找比枢轴大的
			while (arr[left]<=pivot&&left<right)
				left++;
			//找到左边比枢轴大的,扔到右边去
			if(left<right){
				arr[right]=arr[left];
				right--;
			}
			
			while(arr[right]>=pivot&&left<right)
				right--;
			//找到右边的比枢轴小的扔到左边去
			if(left<right){
				arr[left]=arr[right];
				left++;
			}
		}
		arr[left]=pivot;
		return left;
	}
	
}
class Left_Right{
	int left;
	int right;
	public Left_Right(int left,int right){
		this.right = right;
		this.left = left;
	}
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

西门吹水之城

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值