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]