-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathExample144.java
More file actions
58 lines (48 loc) · 1.75 KB
/
Example144.java
File metadata and controls
58 lines (48 loc) · 1.75 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
// Example 144 from page 115
//
import java.util.*;
// Generic quicksort in functional style (the most efficient one)
class Example144 {
public static void main(String[] args) {
Integer[] ia = { 5, 7, 3, 9, 12, 45, 4, 8 };
qsort(ia, new IntegerComparator(), 0, ia.length-1);
Example144.<Integer>qsort(ia, new IntegerComparator(), 0, ia.length-1);
Example144.qsort(ia, new IntegerComparator(), 0, ia.length-1);
for (int i : ia)
System.out.print(i + " ");
System.out.println();
String[] sa = { "New York", "Rome", "Dublin", "Riyadh", "Tokyo" };
Example144.qsort(sa, new StringReverseComparator(), 0, sa.length-1);
for (String s : sa)
System.out.print(s + " ");
System.out.println();
}
// Generic functional-style quicksort: sorts arr[a..b]
private static <T> void qsort(T[] arr, Comparator<T> cmp, int a, int b) {
if (a < b) {
int i = a, j = b;
T x = arr[(i+j) / 2];
do {
while (cmp.compare(arr[i], x) < 0) i++;
while (cmp.compare(x, arr[j]) < 0) j--;
if (i <= j) {
T tmp = arr[i]; arr[i] = arr[j]; arr[j] = tmp;
i++; j--;
}
} while (i <= j);
qsort(arr, cmp, a, j);
qsort(arr, cmp, i, b);
}
}
}
// Comparators for Integer and String
class IntegerComparator implements Comparator<Integer> {
public int compare(Integer v1, Integer v2) {
return v1 < v2 ? -1 : v1 > v2 ? +1 : 0;
}
}
class StringReverseComparator implements Comparator<String> {
public int compare(String v1, String v2) {
return v2.compareTo(v1);
}
}