mirror of
https://github.com/TheAlgorithms/Java.git
synced 2025-07-08 02:04:31 +08:00
Merge pull request #786 from CN-GuoZiyang/master
Using randomize partition to avoid the basically ordered sequences
This commit is contained in:
@ -33,12 +33,27 @@ class QuickSort implements SortAlgorithm {
|
||||
|
||||
private static <T extends Comparable<T>> 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 <T extends Comparable<T>> 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 @@ class QuickSort implements SortAlgorithm {
|
||||
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);
|
||||
|
Reference in New Issue
Block a user