From 7cd855250222df3e467d00920e68f087541e677a Mon Sep 17 00:00:00 2001 From: CN-GuoZiyang Date: Sat, 6 Jul 2019 20:54:55 +0800 Subject: [PATCH 1/2] Using randomize partition to avoid the basically ordered sequences --- Sorts/QuickSort.java | 21 ++++++++++++++++++--- 1 file changed, 18 insertions(+), 3 deletions(-) diff --git a/Sorts/QuickSort.java b/Sorts/QuickSort.java index 373da49462b8..4388d02bf639 100644 --- a/Sorts/QuickSort.java +++ b/Sorts/QuickSort.java @@ -1,6 +1,6 @@ package Sorts; -import static Sorts.SortUtils.*; +import static sorts.SortUtils.*; /** * @author Varun Upadhyay (https://github.com/varunu28) @@ -33,12 +33,27 @@ public > T[] sort(T[] array) { private static > void doSort(T[] array, int left, int right) { if (left < right) { - int pivot = partition(array, left, right); + int pivot = randomPartition(array, left, right); doSort(array, left, pivot - 1); doSort(array, pivot, right); } } + /** + * Ramdomize the array to avoid the basically ordered sequences + * + * @param array The array to be sorted + * @param left The first index of an array + * @param right The last index of an array + * @return the partition index of the array + */ + + private static > int randomPartition(T[] array, int left, int right) { + int randomIndex = left + (int)(Math.random()*(right - left + 1)); + swap(array, randomIndex, right); + return partition(array, left, right); + } + /** * This method finds the partition index for an array * @@ -75,7 +90,7 @@ public static void main(String[] args) { Integer[] array = {3, 4, 1, 32, 0, 1, 5, 12, 2, 5, 7, 8, 9, 2, 44, 111, 5}; QuickSort quickSort = new QuickSort(); - // quickSort.sort(array); + quickSort.sort(array); //Output => 0 1 1 2 2 3 4 5 5 5 7 8 9 12 32 44 111 print(array); From 0821df893ae6ed54c30cc2397fc64f9a45e53bcf Mon Sep 17 00:00:00 2001 From: Guo Ziyang Date: Sat, 6 Jul 2019 20:56:05 +0800 Subject: [PATCH 2/2] Update QuickSort.java --- Sorts/QuickSort.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Sorts/QuickSort.java b/Sorts/QuickSort.java index 4388d02bf639..47f79de0c35d 100644 --- a/Sorts/QuickSort.java +++ b/Sorts/QuickSort.java @@ -1,6 +1,6 @@ package Sorts; -import static sorts.SortUtils.*; +import static Sorts.SortUtils.*; /** * @author Varun Upadhyay (https://github.com/varunu28)