forked from andrei-punko/java-interview-coding
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMergeSort.java
More file actions
55 lines (45 loc) · 1.33 KB
/
Copy pathMergeSort.java
File metadata and controls
55 lines (45 loc) · 1.33 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
package by.andd3dfx.sorting;
import java.util.Arrays;
public class MergeSort {
public static <T extends Comparable> void apply(T[] items) {
int n = items.length;
if (n < 2) {
return;
}
int mid = n / 2;
var left = Arrays.copyOfRange(items, 0, mid);
var right = Arrays.copyOfRange(items, mid, n);
apply(left);
apply(right);
merge(items, left, right);
}
private static <T extends Comparable> void merge(T[] items, T[] left, T[] right) {
int leftLength = left.length;
int rightLength = right.length;
int i = 0, j = 0, k = 0;
while (i < leftLength && j < rightLength) {
if (lessOrEqualsThan(left[i], right[j])) {
items[k] = left[i];
k++;
i++;
} else {
items[k] = right[j];
k++;
j++;
}
}
while (i < leftLength) {
items[k] = left[i];
k++;
i++;
}
while (j < rightLength) {
items[k] = right[j];
k++;
j++;
}
}
private static <T extends Comparable> boolean lessOrEqualsThan(T a, T b) {
return a.compareTo(b) <= 0;
}
}