Skip to content

Commit fddc291

Browse files
committed
modify code
1 parent a307259 commit fddc291

File tree

1 file changed

+33
-3
lines changed

1 file changed

+33
-3
lines changed

src/class05/Code03_QuickSortRecursiveAndUnrecursive.java

Lines changed: 33 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
package class05;
22

3+
import java.util.LinkedList;
4+
import java.util.Queue;
35
import java.util.Stack;
46

57
public class Code03_QuickSortRecursiveAndUnrecursive {
@@ -64,7 +66,7 @@ public Op(int left, int right) {
6466
}
6567
}
6668

67-
// 快排3.0 非递归版本
69+
// 快排3.0 非递归版本 用栈来执行
6870
public static void quickSort2(int[] arr) {
6971
if (arr == null || arr.length < 2) {
7072
return;
@@ -78,7 +80,7 @@ public static void quickSort2(int[] arr) {
7880
stack.push(new Op(0, el - 1));
7981
stack.push(new Op(er + 1, N - 1));
8082
while (!stack.isEmpty()) {
81-
Op op = stack.pop(); // op.l ... op.r
83+
Op op = stack.pop(); // op.l ... op.r
8284
if (op.l < op.r) {
8385
swap(arr, op.l + (int) (Math.random() * (op.r - op.l + 1)), op.r);
8486
equalArea = netherlandsFlag(arr, op.l, op.r);
@@ -90,6 +92,32 @@ public static void quickSort2(int[] arr) {
9092
}
9193
}
9294

95+
// 快排3.0 非递归版本 用队列来执行
96+
public static void quickSort3(int[] arr) {
97+
if (arr == null || arr.length < 2) {
98+
return;
99+
}
100+
int N = arr.length;
101+
swap(arr, (int) (Math.random() * N), N - 1);
102+
int[] equalArea = netherlandsFlag(arr, 0, N - 1);
103+
int el = equalArea[0];
104+
int er = equalArea[1];
105+
Queue<Op> queue = new LinkedList<>();
106+
queue.offer(new Op(0, el - 1));
107+
queue.offer(new Op(er + 1, N - 1));
108+
while (!queue.isEmpty()) {
109+
Op op = queue.poll();
110+
if (op.l < op.r) {
111+
swap(arr, op.l + (int) (Math.random() * (op.r - op.l + 1)), op.r);
112+
equalArea = netherlandsFlag(arr, op.l, op.r);
113+
el = equalArea[0];
114+
er = equalArea[1];
115+
queue.offer(new Op(op.l, el - 1));
116+
queue.offer(new Op(er + 1, op.r));
117+
}
118+
}
119+
}
120+
93121
// 生成随机数组(用于测试)
94122
public static int[] generateRandomArray(int maxSize, int maxValue) {
95123
int[] arr = new int[(int) ((maxSize + 1) * Math.random())];
@@ -151,9 +179,11 @@ public static void main(String[] args) {
151179
for (int i = 0; i < testTime; i++) {
152180
int[] arr1 = generateRandomArray(maxSize, maxValue);
153181
int[] arr2 = copyArray(arr1);
182+
int[] arr3 = copyArray(arr1);
154183
quickSort1(arr1);
155184
quickSort2(arr2);
156-
if (!isEqual(arr1, arr2)) {
185+
quickSort3(arr3);
186+
if (!isEqual(arr1, arr2) || !isEqual(arr1, arr3)) {
157187
succeed = false;
158188
break;
159189
}

0 commit comments

Comments
 (0)