
public class Shell {
public static void sort(Comparable[] a) {
// 根据数组a的长度,确定增长量h的初值
int h = 1;
while (h < a.length / 2) {
h = 2 * h + 1;
}
// 希尔排序
while (h >= 1) {
//排序
// 找到待插入的元素
for (int i = h; i < a.length; i++){
// 把待插入的元素插入到有序数列中
for (int j = i; j >= h; j -= h) {
//待插入的元素是a[j],比较a[j]和a[j-h]
if (greater(a[j - h], a[j])) {
exch(a, j - h, j);
} else {
// 结束循环
break;
}
}
}
// 减小h的值
h = h / 2;
}
}
private static boolean greater(Comparable v, Comparable w) {
return v.compareTo(w) > 0;
}
private static void exch(Comparable[] a, int i, int j) {
Comparable temp;
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
import java.util.Arrays;
public class ShellTest {
public static void main(String[] args) {
Integer[] a={9,1,2,3,5,8,6,7,4,5};
Shell.sort(a);
System.out.println(Arrays.toString(a));
}
}
D:javajdkjdk-14.0.2binjava.exe "-javaagent:D:ideaIC-2021.2.2IDEAIntelliJ IDEA 2020.1.1libidea_rt.jar=53180:D:ideaIC-2021.2.2IDEAIntelliJ IDEA 2020.1.1bin" -Dfile.encoding=UTF-8 -classpath E:ideaProjectitcastoutproductiondata_structure ShellTest
[1, 2, 3, 4, 5, 5, 6, 7, 8, 9]
Process finished with exit code 0