-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathQuickSort.java
More file actions
57 lines (48 loc) · 1.38 KB
/
QuickSort.java
File metadata and controls
57 lines (48 loc) · 1.38 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
57
import java.util.Comparator;
public class QuickSort {
private static long comparisons = 0;
public static <K> void sort(K[] S, Comparator<K> comp) {
comparisons = 0;
quickSortInPlace(S, comp, 0, S.length - 1);
}
private static <K> void quickSortInPlace(K[] S, Comparator<K> comp, int a, int b) {
if (a >= b) return;
int left = a;
int right = b - 1;
K pivot = S[b];
K temp;
while (left <= right) {
while (left <= right) {
comparisons++;
if (comp.compare(S[left], pivot) < 0) {
left++;
} else {
break;
}
}
while (left <= right) {
comparisons++;
if (comp.compare(S[right], pivot) > 0) {
right--;
} else {
break;
}
}
if (left <= right) {
temp = S[left];
S[left] = S[right];
S[right] = temp;
left++;
right--;
}
}
temp = S[left];
S[left] = S[b];
S[b] = temp;
quickSortInPlace(S, comp, a, left - 1);
quickSortInPlace(S, comp, left + 1, b);
}
public static long getComparisons() {
return comparisons;
}
}