1+ /*********************************************************************************
2+ * (Improve quick sort) The quick sort algorithm presented in the book selects *
3+ * the first element in the list as the pivot. Revise it by selecting the median *
4+ * among the first, middle, and last elements in the list. *
5+ *********************************************************************************/
6+ public class Exercise_23_04 {
7+ public static void quickSort (int [] list ) {
8+ quickSort (list , 0 , list .length - 1 );
9+ }
10+
11+ public static void quickSort (int [] list , int first , int last ) {
12+ if (last > first ) {
13+ int pivotIndex = partition (list , first , last );
14+ quickSort (list , first , pivotIndex - 1 );
15+ quickSort (list , pivotIndex + 1 , last );
16+ }
17+ }
18+
19+ /** Partition the aray list[first..last] */
20+ public static int partition (int [] list , int first , int last ) {
21+ int middle = list [(list .length - 1 ) / 2 ];
22+ // choose the median element as the pivot
23+ int pivot = median (first , middle , last );
24+ int low = first + 1 ; // Index for forward search
25+ int high = last ; // Index for backward search
26+
27+ while (high > low ) {
28+ // Search forward from left
29+ while (low <= high && list [low ] <= pivot )
30+ low ++;
31+
32+ // Search backward from right
33+ while (low <= high && list [high ] > pivot )
34+ high --;
35+
36+ // Swap two elements in the list
37+ if (high > low ) {
38+ int temp = list [high ];
39+ list [high ] = list [low ];
40+ list [low ] = temp ;
41+ }
42+ }
43+
44+ while (high > first && list [high ] >= pivot )
45+ high --;
46+
47+ // Swap pivot with list[high]
48+ if (pivot > list [high ]) {
49+ list [first ] = list [high ];
50+ list [high ] = pivot ;
51+ return high ;
52+ }
53+ else {
54+ return first ;
55+ }
56+ }
57+
58+ /** A test method */
59+ public static void main (String [] args ) {
60+ int [] list = {2 , 3 , 2 , 5 , 6 , 1 , -2 , 3 , 14 , 12 };
61+ quickSort (list );
62+ for (int i = 0 ; i < list .length ; i ++)
63+ System .out .print (list [i ] + " " );
64+ System .out .println ();
65+ }
66+
67+ /** Returns the median of three integers */
68+ public static int median (int first , int middle , int last ) {
69+ return Math .max (Math .min (first , middle ),
70+ Math .min (Math .max (first , middle ), last ));
71+ }
72+ }
0 commit comments