forked from andrei-punko/java-interview-coding
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathQuickSort.java
More file actions
53 lines (44 loc) · 1.36 KB
/
Copy pathQuickSort.java
File metadata and controls
53 lines (44 loc) · 1.36 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
package by.andd3dfx.sorting;
public class QuickSort {
public static <T extends Comparable> void apply(T[] items) {
quickSort(items, 0, items.length - 1);
}
private static <T extends Comparable> void quickSort(T[] items, int low, int high) {
if (low < high) {
int p = partition(items, low, high);
quickSort(items, low, p);
quickSort(items, p + 1, high);
}
}
private static <T extends Comparable> int partition(T[] items, int low, int high) {
var v = items[(low + high) / 2];
int i = low;
int j = high;
while (i <= j) {
while (lessThan(items[i], v)) {
i++;
}
while (greaterThan(items[j], v)) {
j--;
}
if (i >= j) {
break;
}
swap(items, i, j);
i++;
j--;
}
return j;
}
private static <T extends Comparable> boolean lessThan(T a, T b) {
return a.compareTo(b) < 0;
}
private static <T extends Comparable> boolean greaterThan(T a, T b) {
return a.compareTo(b) > 0;
}
private static <T> void swap(T[] items, int i, int j) {
var tmp = items[i];
items[i] = items[j];
items[j] = tmp;
}
}