99import static array .visualizer .ArrayVisualizer .*;
1010import static array .visualizer .utils .Analysis .*;
1111import static array .visualizer .utils .Swaps .*;
12+ import java .util .Queue ;
13+ import java .util .LinkedList ;
1214
1315/**
16+ * Binary MSD Radix Sort / Binary Quicksort.
17+ *
18+ * Implemented as recursive decent, and via task queue, see:
19+ * * binaryQuickSortRecursive, and
20+ * * binaryQuickSort respectively.
21+ *
22+ * Both of which are in-place sorting algorithms, with the recursive utilizing
23+ * the stack for divide-and-conquer, while the non-recursive utilizes a queue.
24+ *
25+ * Can be extended to support unsigned integers, by sorting the first bit rin
26+ * reverse. Can be made stable at the cost of O(n) memory. Can be parallalized
27+ * to O(log2(n)) subtasks / threads.
1428 *
1529 * @author Skeen
1630 */
@@ -33,14 +47,45 @@ public static int analyzeBit(final ArrayController ac) {
3347 return 31 - Integer .numberOfLeadingZeros (max );
3448 }
3549
36- public static void binaryQuickSort (final ArrayController ac , int p , int r , int bit )
50+ public static class Task {
51+ public int p ;
52+ public int r ;
53+ public int bit ;
54+
55+ public Task (int p , int r , int bit )
56+ {
57+ this .p = p ;
58+ this .r = r ;
59+ this .bit = bit ;
60+ }
61+ }
62+
63+ public static void binaryQuickSortRecursive (final ArrayController ac , int p , int r , int bit )
3764 {
3865 if (p < r && bit >= 0 )
3966 {
4067 int q =partition (ac , p , r , bit );
4168 sleep (1 );
42- binaryQuickSort (ac , p , q , bit -1 );
43- binaryQuickSort (ac , q +1 , r , bit -1 );
69+ binaryQuickSortRecursive (ac , p , q , bit -1 );
70+ binaryQuickSortRecursive (ac , q +1 , r , bit -1 );
71+ }
72+ }
73+
74+ public static void binaryQuickSort (final ArrayController ac , int p , int r , int bit )
75+ {
76+ Queue <Task > tasks = new LinkedList <Task >();
77+ tasks .add (new Task (p , r , bit ));
78+
79+ while (tasks .isEmpty () == false )
80+ {
81+ Task task = tasks .remove ();
82+ if (task .p < task .r && task .bit >= 0 )
83+ {
84+ int q =partition (ac , task .p , task .r , task .bit );
85+ sleep (1 );
86+ tasks .add (new Task (task .p , q , task .bit -1 ));
87+ tasks .add (new Task (q +1 , task .r , task .bit -1 ));
88+ }
4489 }
4590 }
4691
@@ -85,5 +130,6 @@ public void sort(ArrayController ac)
85130 {
86131 int msb = analyzeBit (ac );
87132 binaryQuickSort (ac , 0 , ac .length -1 , msb );
133+ // binaryQuickSortRecursive(ac, 0, ac.length-1, msb);
88134 }
89135}
0 commit comments