希尔排序java实现
具体代码实现如下
/**
* @author shkstart
* @create 2021-03-22 16:43
*/
public class ShellSort2 {
public static void shellSort(int[] arrays) {
//增量每次都/2
for (int step = arrays.length / 2; step > 0; step /= 2) {
//从增量那组开始进行插入排序,直至完毕
for (int i = step; i < arrays.length; i++) {
int j = i;
int temp = arrays[j];
// j - step 就是代表与它同组隔壁的元素
while (j - step >= 0 && arrays[j - step] > temp) {
arrays[j] = arrays[j - step];
j = j - step;
}
arrays[j] = temp;
}
}
}
public static void main(String[] args) {
int[] arr = new int[10];
for (int n=0;n<arr.length;n++){
arr[n] = (int)(Math.random()*10000);
}
System.out.println(Arrays.toString(arr)+"\n");
shellSort(arr);
System.out.println(Arrays.toString(arr));
}
}
希尔排序里面沿用了插入排序的原理。我在理解这个代码的过程中,for循环内step值的变化刚开始理解得很不到位(暴露出基础问题)
在for循环体中,只有内容执行完毕后,才会执行for(a;b;c)中的c语句,而a语句在很多时候只是初始赋值的语句,在这个算法中因为这个基础的问题花了我不少时间。