原理:(1)选定一个 增长量h,按照增长量h作为数据分组的依据,对数据进行分组。
(2)对分好组的每一组数据完成插入排序。
(3)减小增长量,最小减为1,重复第二步操作。
时间复杂度: O(n^2)
Java代码实现(附测试案例):
package day02;
public class Shell {
public static void sort(Comparable[] a) {
//1.根据数组a的长度,确定增长量h的初始值
int h=1;
while (h < a.length / 2) {
h=2*h+1;
}
//2.希尔排序
while (h >= 1) {
//找到带插入的元素
for (int i = h; i < a.length; i++) {
//把待插入的元素插入到有序数列中
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/2; //减小h的值
}
}
//比较v元素是否大于w元素
private static boolean greater(Comparable v, Comparable w) {
return v.compareTo(w)>0;
}
//数组元素i和j交换位置
private static void exch(Comparable[] a, int i, int j) {
Comparable temp;
temp=a[i];
a[i]=a[j];
a[j]=temp;
}
}
package test;
import java.util.Arrays;
import day02.Shell;
public class ShellTest {
public static void main(String[] args) {
Integer[] arr = {9, 1, 2, 5, 7, 4, 8, 6, 3, 5};
Shell.sort(arr);
System.out.println(Arrays.toString(arr));
}
}

被折叠的 条评论
为什么被折叠?



