【Java 算法】快速排序(递归&非递归思想版本)

import java.util.Arrays;
import java.util.LinkedList;
import java.util.Queue;

public class 快速排序 {

	public static void main(String[] args) {
//		int[] arr = {99, 88, 77, 66, 55, 44, 33, 22, 11};
		int[] arr = {34, 43, 87, 98, 60, 50, 66, 77, 88, 4};
		quickSortStack(arr);
		System.out.println(Arrays.toString(arr));
	}
	
	public static void quickSort(int[] arr) {
		quickSort(arr, 0, arr.length - 1);
	}
	
	public static void quickSort(int[] arr, int left, int right) { //优化版
		//二分每次最左边的数作为基数
//		int base = arr[left]; //完全可以省略的基数临时存储,因为如果要交换基数时,必然 i == j,也就是while()循环中是不会做操作
		int i = left;
		int j = right;
		while (i < j) { //实行检查交换, 基数从最左边开始时,一定要让 j 先走
			while (arr[j] >= arr[left] && j > i) j--; //寻找小于 base 的数
			while (arr[i] <= arr[left] && i < j) i++; //寻找大于 base 的数
			if (i < j) { //交换
				swap(arr, i, j);
			}
		}
		//交换基数
		if (i != left) { //基数自己不需要交换
			swap(arr, left, i);
		}
		System.out.println(Arrays.toString(arr));
		if (left < i - 1) quickSort(arr, left, i - 1);
		if (i + 1 < right) quickSort(arr, i + 1, right);
	}
	
	public static void swap(int[] arr, int a, int b) {
		arr[a] = arr[a] ^ arr[b];
		arr[b] = arr[a] ^ arr[b];
		arr[a] = arr[a] ^ arr[b];
	}
	
	static class Quick {
		public int startIndex;
		public int endIndex;
		public Quick(int startIndex, int endIndex) {
			this.startIndex = startIndex;
			this.endIndex = endIndex;
		}
	}
	
	public static void quickSortStack(int[] arr) { //Stack 非递归优化版
//		Stack<Quick> stack = new Stack<>();
		Queue<Quick> stack = new LinkedList<>();
		stack.offer(new Quick(0, arr.length - 1));
		while (! stack.isEmpty()) {
			Quick pop = stack.poll(); //快速排序直接取出即可,因为只有区间排序
			//二分每次最左边的数作为基数
			int i = pop.startIndex;
			int j = pop.endIndex;
			while (i < j) { //实行检查交换, 基数从最左边开始时,一定要让 j 先走
				while (arr[j] >= arr[pop.startIndex] && j > i) j--; //寻找小于 base 的数
				while (arr[i] <= arr[pop.startIndex] && i < j) i++; //寻找大于 base 的数
				if (i < j) { //交换
					swap(arr, i, j);
				}
			}
			//交换基数
			if (i != pop.startIndex) { //基数自己不需要交换
				swap(arr, pop.startIndex, i);
			}
			if (pop.startIndex < i - 1) { //压栈左区间
				stack.offer(new Quick(pop.startIndex, i - 1));
			}
			if (i + 1 < pop.endIndex) { //压栈右区间
				stack.offer(new Quick(i + 1, pop.endIndex));
			}
		}
	}

}

输出

[4, 34, 43, 50, 60, 66, 77, 87, 88, 98]

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

虚妄狼

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

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

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

打赏作者

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

抵扣说明:

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

余额充值