Skip to content

Commit 0ff74ca

Browse files
optimization
1 parent dc6f830 commit 0ff74ca

File tree

1 file changed

+14
-22
lines changed

1 file changed

+14
-22
lines changed

Sorts/ShellSort.java

+14-22
Original file line numberDiff line numberDiff line change
@@ -2,48 +2,40 @@
22

33
import static Sorts.SortUtils.*;
44

5-
6-
/**
7-
* @author dpunosevac
8-
* @author Podshivalov Nikita (https://github.com/nikitap492)
9-
* @see SortAlgorithm
10-
*/
115
public class ShellSort implements SortAlgorithm {
126

137
/**
148
* This method implements Generic Shell Sort.
159
*
16-
* @param array The array to be sorted
10+
* @param array the array to be sorted
1711
*/
1812
@Override
1913
public <T extends Comparable<T>> T[] sort(T[] array) {
20-
int N = array.length;
21-
int h = 1;
14+
int length = array.length;
15+
int gap = 1;
2216

23-
while (h < N / 3) {
24-
h = 3 * h + 1;
17+
/* Calculate gap for optimization purpose */
18+
while (gap < length / 3) {
19+
gap = 3 * gap + 1;
2520
}
2621

27-
while (h >= 1) {
28-
for (int i = h; i < N; i++) {
29-
for (int j = i; j >= h && less(array[j], array[j - h]); j -= h) {
30-
swap(array, j, j - h);
22+
for (; gap > 0; gap /= 3) {
23+
for (int i = gap; i < length; i++) {
24+
int j;
25+
for (j = i; j >= gap && less(array[j], array[j - gap]); j -= gap) {
26+
array[j] = array[j - gap];
3127
}
28+
array[j] = array[i];
3229
}
33-
34-
h /= 3;
3530
}
36-
3731
return array;
3832
}
3933

34+
/* Driver Code */
4035
public static void main(String[] args) {
4136
Integer[] toSort = {4, 23, 6, 78, 1, 54, 231, 9, 12};
4237

4338
ShellSort sort = new ShellSort();
44-
Integer[] sorted = sort.sort(toSort);
45-
46-
print(sorted);
47-
39+
print(sort.sort(toSort));
4840
}
4941
}

0 commit comments

Comments
 (0)