图片上第一趟排序的步长应该是7.
import java.util.Arrays;
public class ShellSort {
public static void main(String[] args) {
Integer[] a = {1,3,5,7,9,2,4,6,8,10};
shellSort(a);
System.out.println(Arrays.toString(a));
}
public static void shellSort(Comparable[] a) {
//根据数组长度确定增长量h
int h = 1;
while (h < a.length / 2) {
h = 2 * h + 1;
}
//做希尔排序
while (h >= 1) {
//找到带排序元素
for (int i = h; i < a.length; i++) {
//将待排序元素插入进去
for (int j = i; j >= h; j -= h) {
if (greater(a[j - h], a[j])) {
exch(a, j-h , j);
} else {
break;
}
}
}
//减小步长
h = h/ 2;
}
}
private static boolean greater(Comparable v, Comparable w) {
return v.compareTo(w) > 0;
}
private static void exch(Comparable[] a, int i, int j) {
Comparable temp;
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
解释稍微详细一点的
public static void shellSort(Comparable[] a){
//1.根据数组a的长度,确定增长量h的初始值;
int h = 1;
while(h<a.length/2){
h=2*h+1;
}
//2.希尔排序
while(h>=1){
//排序
//2.1.找到待插入的元素
for (int i=h;i<a.length;i++){
//2.2把待插入的元素插入到有序数列中
for (int j=i;j>=h;j-=h){
//待插入的元素是a[j],比较a[j]和a[j-h]
if (greater(a[j-h],a[j])){
//交换元素
exch(a,j-h,j);
}else{
//待插入元素已经找到了合适的位置,结束循环;
break;
}
}
}
//减小h的值
h= h/2;
}
}