@@ -33,12 +33,27 @@ public <T extends Comparable<T>> T[] sort(T[] array) {
33
33
34
34
private static <T extends Comparable <T >> void doSort (T [] array , int left , int right ) {
35
35
if (left < right ) {
36
- int pivot = partition (array , left , right );
36
+ int pivot = randomPartition (array , left , right );
37
37
doSort (array , left , pivot - 1 );
38
38
doSort (array , pivot , right );
39
39
}
40
40
}
41
41
42
+ /**
43
+ * Ramdomize the array to avoid the basically ordered sequences
44
+ *
45
+ * @param array The array to be sorted
46
+ * @param left The first index of an array
47
+ * @param right The last index of an array
48
+ * @return the partition index of the array
49
+ */
50
+
51
+ private static <T extends Comparable <T >> int randomPartition (T [] array , int left , int right ) {
52
+ int randomIndex = left + (int )(Math .random ()*(right - left + 1 ));
53
+ swap (array , randomIndex , right );
54
+ return partition (array , left , right );
55
+ }
56
+
42
57
/**
43
58
* This method finds the partition index for an array
44
59
*
@@ -75,7 +90,7 @@ public static void main(String[] args) {
75
90
Integer [] array = {3 , 4 , 1 , 32 , 0 , 1 , 5 , 12 , 2 , 5 , 7 , 8 , 9 , 2 , 44 , 111 , 5 };
76
91
77
92
QuickSort quickSort = new QuickSort ();
78
- // quickSort.sort(array);
93
+ quickSort .sort (array );
79
94
80
95
//Output => 0 1 1 2 2 3 4 5 5 5 7 8 9 12 32 44 111
81
96
print (array );
0 commit comments