11package class05 ;
22
3+ import java .util .LinkedList ;
4+ import java .util .Queue ;
35import java .util .Stack ;
46
57public class Code03_QuickSortRecursiveAndUnrecursive {
@@ -64,7 +66,7 @@ public Op(int left, int right) {
6466}
6567}
6668
67- // 快排3.0 非递归版本
69+ // 快排3.0 非递归版本 用栈来执行
6870public static void quickSort2 (int [] arr ) {
6971if (arr == null || arr .length < 2 ) {
7072return ;
@@ -78,7 +80,7 @@ public static void quickSort2(int[] arr) {
7880stack .push (new Op (0 , el - 1 ));
7981stack .push (new Op (er + 1 , N - 1 ));
8082while (!stack .isEmpty ()) {
81- Op op = stack .pop (); // op.l ... op.r
83+ Op op = stack .pop (); // op.l ... op.r
8284if (op .l < op .r ) {
8385swap (arr , op .l + (int ) (Math .random () * (op .r - op .l + 1 )), op .r );
8486equalArea = 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// 生成随机数组(用于测试)
94122public static int [] generateRandomArray (int maxSize , int maxValue ) {
95123int [] arr = new int [(int ) ((maxSize + 1 ) * Math .random ())];
@@ -151,9 +179,11 @@ public static void main(String[] args) {
151179for (int i = 0 ; i < testTime ; i ++) {
152180int [] arr1 = generateRandomArray (maxSize , maxValue );
153181int [] arr2 = copyArray (arr1 );
182+ int [] arr3 = copyArray (arr1 );
154183quickSort1 (arr1 );
155184quickSort2 (arr2 );
156- if (!isEqual (arr1 , arr2 )) {
185+ quickSort3 (arr3 );
186+ if (!isEqual (arr1 , arr2 ) || !isEqual (arr1 , arr3 )) {
157187succeed = false ;
158188break ;
159189}
0 commit comments