排序原理:
1.选定一个增长量h,按照增长量h作为数据分组的依据,对数据进行分组;
2.对分好组的每一组数据完成插入排序;
3.减小增长量,最小减为1,重复第二步操作。
排序过程:
例:{9,1,2,5,7,4,8,6,3,5}
package com.sort;
public class ShellSort {
public static void shellSort(Comparable[] comparables) {
int h = 1;
int length = comparables.length;
while (h < length / 2) {
h = (h * 2 + 1);
}
while (h >= 1) {
for (int i = h; i < length; i++) {
for (int j = i; j >= h; j -= h) {
if (Comparable(comparables[j - h], comparables[j])) {
exchange(comparables, j - h, j);
} else {
break;
}
}
}
h /= 2;
}
}
public static boolean Comparable(Comparable comparable1, Comparable comparable2) {
return comparable1.compareTo(comparable2) > 0;
}
public static void exchange(Comparable[] comparable, int leftIndex, int rightIndex) {
Comparable temp;
temp = comparable[leftIndex];
comparable[leftIndex] = comparable[rightIndex];
comparable[rightIndex] = temp;
}
}
测试类:
package com.testsort;
import java.util.Arrays;
import static com.sort.ShellSort.shellSort;
public class TestShell {
public static void main(String[] args) {
Integer[] array = {4,6,8,7,9,2,10,1};
shellSort(array);
System.out.println(Arrays.toString(array));
}
}