@@ -33,12 +33,27 @@ public <T extends Comparable<T>> T[] sort(T[] array) {
3333
3434 private static <T extends Comparable <T >> void doSort (T [] array , int left , int right ) {
3535 if (left < right ) {
36- int pivot = partition (array , left , right );
36+ int pivot = randomPartition (array , left , right );
3737 doSort (array , left , pivot - 1 );
3838 doSort (array , pivot , right );
3939 }
4040 }
4141
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+
4257 /**
4358 * This method finds the partition index for an array
4459 *
@@ -75,7 +90,7 @@ public static void main(String[] args) {
7590 Integer [] array = {3 , 4 , 1 , 32 , 0 , 1 , 5 , 12 , 2 , 5 , 7 , 8 , 9 , 2 , 44 , 111 , 5 };
7691
7792 QuickSort quickSort = new QuickSort ();
78- // quickSort.sort(array);
93+ quickSort .sort (array );
7994
8095 //Output => 0 1 1 2 2 3 4 5 5 5 7 8 9 12 32 44 111
8196 print (array );
0 commit comments