希尔排序
![](https://uploadfiles.nowcoder.com/images/20210410/613861755_1618034626390_40E8BDE20D7222A16DA28374800F45E8)
![](https://uploadfiles.nowcoder.com/images/20210410/613861755_1618034626942_014AA794B8DE2B0593F9F6C4BE7243D9)
![](https://uploadfiles.nowcoder.com/images/20210410/613861755_1618034627206_DA12E9E1A346E3F0CDAB39A933BE38F2)
/*
* 希尔排序
*/
public class ShellSort {
/**
* 排序方法
*/
public static void sort(long[] arr) {
//初始化一个间隔
int h = 1;
//计算最大间隔
while(h < arr.length / 3) {
h = h * 3 + 1;
}
while(h > 0) {
//进行插入排序
long tmp = 0;
for(int i = h; i < arr.length; i++) {
tmp = arr[i];
int j = i;
while(j > h - 1 && arr[j - h] >= tmp) {
arr[j] = arr[j - h];
j -= h;
}
arr[j] = tmp;
}
//减小间隔
h = (h - 1) / 3;
}
}
}
public class TestShellSort {
public static void main(String[] args) {
long[] arr = new long[10];
arr[0] = 90;
arr[1] = 12;
arr[2] = 23;
arr[3] = 15;
arr[4] = -4;
arr[5] = 1;
arr[6] = 97;
arr[7] = 4;
arr[8] = 3;
arr[9] = 8;
System.out.print("[");
for(long num : arr) {
System.out.print(num + " ");
}
System.out.print("]");
System.out.println();
ShellSort.sort(arr);
System.out.print("[");
for(long num : arr) {
System.out.print(num + " ");
}
System.out.print("]");
System.out.println();
}
}
![](https://uploadfiles.nowcoder.com/images/20210410/613861755_1618034627454_B92FF0C665A5479716A0FB6245CDB583)
![](https://uploadfiles.nowcoder.com/images/20210410/613861755_1618034627523_014AA794B8DE2B0593F9F6C4BE7243D9)