JavaAlgorithms/Sorts/ShellSort.java

43 lines
1.0 KiB
Java
Raw Normal View History

2018-11-14 01:15:47 +08:00
package Sorts;
2017-09-29 00:33:36 +08:00
2018-11-14 01:15:47 +08:00
import static Sorts.SortUtils.*;
public class ShellSort implements SortAlgorithm {
2017-09-29 00:33:36 +08:00
/**
* This method implements Generic Shell Sort.
*
2020-01-11 14:19:49 +08:00
* @param array the array to be sorted
*/
@Override
public <T extends Comparable<T>> T[] sort(T[] array) {
2020-01-11 14:19:49 +08:00
int length = array.length;
int gap = 1;
2020-01-11 14:19:49 +08:00
/* Calculate gap for optimization purpose */
while (gap < length / 3) {
gap = 3 * gap + 1;
}
2017-09-29 00:33:36 +08:00
2020-01-11 14:19:49 +08:00
for (; gap > 0; gap /= 3) {
for (int i = gap; i < length; i++) {
int j;
2020-04-16 21:33:22 +08:00
T temp = array[i];
2020-04-16 21:31:01 +08:00
for (j = i; j >= gap && less(temp, array[j - gap]); j -= gap) {
2020-01-11 14:19:49 +08:00
array[j] = array[j - gap];
}
2020-04-16 21:31:01 +08:00
array[j] = temp;
}
2017-09-29 00:33:36 +08:00
}
return array;
2017-09-29 00:33:36 +08:00
}
2020-01-11 14:19:49 +08:00
/* Driver Code */
public static void main(String[] args) {
Integer[] toSort = {4, 23, 6, 78, 1, 54, 231, 9, 12};
2017-09-29 00:33:36 +08:00
ShellSort sort = new ShellSort();
2020-01-11 14:19:49 +08:00
print(sort.sort(toSort));
}
2017-09-29 00:33:36 +08:00
}