forked from andrei-punko/java-interview-coding
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathShellSort.java
More file actions
31 lines (24 loc) · 844 Bytes
/
Copy pathShellSort.java
File metadata and controls
31 lines (24 loc) · 844 Bytes
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
package by.andd3dfx.sorting;
public class ShellSort {
public static <T extends Comparable> void apply(T[] array) {
int d = 1;
while (d <= array.length / 3) {
d = d * 3 + 1; // (1, 4, 13, 40, 121, ...)
}
while (d > 0) {
for (int outer = d; outer < array.length; outer++) {
var tmp = array[outer];
int inner = outer;
while (inner - d >= 0 && greaterThan(array[inner - d], tmp)) {
array[inner] = array[inner - d];
inner -= d;
}
array[inner] = tmp;
}
d = (d - 1) / 3;
}
}
private static <T extends Comparable> boolean greaterThan(T a, T b) {
return a.compareTo(b) > 0;
}
}