Skip to content

Commit 81692b2

Browse files
committed
add generic quicksort
1 parent 81541bc commit 81692b2

File tree

1 file changed

+57
-0
lines changed

1 file changed

+57
-0
lines changed

src/section21/GenericQuickSort.java

+57
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
package section21;
2+
3+
import java.util.Arrays;
4+
import java.util.Comparator;
5+
6+
/**
7+
* This example demonstrates the syntax for declaring and using generic methods.
8+
*/
9+
public class GenericQuickSort {
10+
11+
/* Quicksorts the entire array using the given comparator */
12+
public static <T> void quickSort(T[] arr, Comparator<T> cmp) {
13+
quickSort(arr, cmp, 0, arr.length - 1);
14+
}
15+
16+
/* Quicksorts the array using the given comparator between start and end index (inclusive) */
17+
private static <T> void quickSort(T[] arr, Comparator<T> cmp, int start, int end) {
18+
if (start >= end) { // empty or singleton case
19+
return;
20+
}
21+
22+
// determine pivot value, start pointer, and end pointer
23+
T pivot = arr[start + (end-start) / 2];
24+
int i = start;
25+
int j = end;
26+
27+
while (i <= j) {
28+
while (cmp.compare(arr[i], pivot) < 0) { i++; }
29+
while (cmp.compare(pivot, arr[j]) < 0) { j--; }
30+
31+
if (i <= j) {
32+
T tmp = arr[i];
33+
arr[i] = arr[j];
34+
arr[j] = tmp;
35+
i++;
36+
j--;
37+
}
38+
}
39+
40+
quickSort(arr, cmp, start, j);
41+
quickSort(arr, cmp, i, end);
42+
43+
}
44+
45+
public static void main(String[] argv) {
46+
Comparator<Integer> desc = new Comparator<Integer>() {
47+
public int compare(Integer x, Integer y) {
48+
return y - x;
49+
}
50+
};
51+
52+
Integer[] arr = new Integer[] { 2, 19, 54, -14, 5, 19, 9351, 1024 };
53+
quickSort(arr, desc); // sort the array in descending order
54+
55+
System.out.println(Arrays.toString(arr));
56+
}
57+
}

0 commit comments

Comments
 (0)