代码实现
package com.atguigu.sort;
import java.util.Arrays;
/**
* @author WHT
* @create 2021-06-17 10:13
*/
public class ShellSort {
public static void main(String[] args) {
int[] arr = {8, 9, 1, 7, 2, 3, 5, 4, 6, 0};
System.out.printf("排序前的数组:");
System.out.println(Arrays.toString(arr));
shellSort(arr);
}
public static void shellSort(int[] arr) {
int flag = 0;
for (int gap = arr.length / 2; gap > 0; gap = gap / 2) {
flag++;
for (int i = gap; i < arr.length; i++) {
int insertVal = arr[i];
for (int j = i - gap; j >= 0; j = j - gap) {
if (insertVal >= arr[j]) {
arr[j + gap] = insertVal;
break;
}
// 移动。
arr[j + gap] = arr[j];
// 如果待插入的数比所有已排序的数都小,将待插入的数插入数组的第一个位置。
if (j < gap) {
arr[j] = insertVal;
}
}
}
System.out.printf("第%d轮后的数组:", flag);
System.out.println(Arrays.toString(arr));
}
}
}
运行结果
D:\java\jdk-11.0.11\bin\java.exe "-javaagent:D:\IntelliJ IDEA 2020.1.1\lib\idea_rt.jar=3977:D:\IntelliJ IDEA 2020.1.1\bin" -Dfile.encoding=UTF-8 -classpath E:\WHT\Project\Java\DataStructures\out\production\DataStructures com.atguigu.sort.ShellSort
排序前的数组:[8, 9, 1, 7, 2, 3, 5, 4, 6, 0]
第1轮后的数组:[3, 5, 1, 6, 0, 8, 9, 4, 7, 2]
第2轮后的数组:[0, 2, 1, 4, 3, 5, 7, 6, 9, 8]
第3轮后的数组:[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Process finished with exit code 0
8万随机数测试:1s 。