import java.util.Arrays;
public class ShellSort {
public static void main(String[] args) {
int[] arr = {4, 34, 19, 1, 9 ,-1};
System.out.println("排序前为:" + Arrays.toString(arr));
shellSort(arr);
System.out.println("排序后为:" + Arrays.toString(arr));
}
public static void shellSort(int[] arr) {
// 设置增量step,逐步缩小增量
for (int step = arr.length / 2; step > 0; step /= 2) {
// 从第step个元素,逐个对其所在的组进行插入排序
// 保证第一次分组之后,可以遍历每一个组
for (int i = step; i < arr.length; i++) {
// 记录将要插入的位置
int j = i - step;
// 记录将要插入的值
int temp = arr[i];
while (j >= 0 && arr[j] > temp) {
// 移动
arr[j + step] = arr[j];
j -= step;
}
if (j != i - step) {
arr[j + step] = temp;
}
}
}
}
}
algorithm:希尔排序
最新推荐文章于 2025-05-09 17:11:59 发布