Skip to content

Commit 2bf163d

Browse files
authored
Merge pull request TheAlgorithms#786 from CN-GuoZiyang/master
Using randomize partition to avoid the basically ordered sequences
2 parents 63cf199 + 0821df8 commit 2bf163d

File tree

1 file changed

+17
-2
lines changed

1 file changed

+17
-2
lines changed

Sorts/QuickSort.java

Lines changed: 17 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -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

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy