希爾排序是屬于插入排序的一種,即分組進(jìn)行插入排序,將大數(shù)和小數(shù)適當(dāng)?shù)姆植加谧笥?,減少插入時(shí)移動(dòng)的次數(shù)
package string.sort.insert;
import java.util.Arrays;
/**
* @author chenyi
* @Description
* @date 2022/2/14 11:36
*/
public class ShellSort {
public void solution(int[] arr) {
// 步長(zhǎng),初始為數(shù)據(jù)長(zhǎng)度的一半
for (int gap = arr.length>>1; gap > 0; gap>>=1) {
for (int i = gap; i < arr.length; i++) {
int temp = arr[i];
// 分組進(jìn)行插入排序,每組第一個(gè)不動(dòng).用排好序的最近一個(gè)數(shù)和當(dāng)前數(shù)比較
int j = i;
while (j-gap>=0 && arr[j-gap]>temp) {
arr[j] = arr[j-gap];
j-=gap;
}
arr[j] = temp;
}
System.out.println(Arrays.toString(arr));
}
}
public static void main(String[] args) throws InterruptedException {
int[] arr = {8,9,1,7,2,3,5,4,6,0};
new ShellSort().solution(arr);
}
}