排序之希尔排序 Java实现

    xiaoxiao2022-07-14  182

    算法:

    一个 h 有序数组就是 h 个互相独立的有序数组编织在一起组成的一个数组。在进行排序是,如果 h很大,我们就能将元素移动到很远的地方,为实现更小的 h 有序创造方便。用这种方式,对任意以1结尾的h序列,我们都能讲数组排序。

    实现:

    使用序列 1/2(-1),从 N/3 开始递减至 1 。这个序列被称为递增序列。

    实现希尔排序的一种方法是对于每个h,用插入排序将h 个子数组独立排序。但是因为子数组是相互独立的,一更更简单的方法是在h- 子数组中将每个元素交换到比它大的元素之前去(将比它大的元素向右移动一格)。再继续要在插入排序的代码将移动元素的距离由 1 改 h 即可。希尔排序的实现就转化为了一个类似于插入排序但使用不同增量的过程。

    public class Shell { public static void sort(Comparable[] a) { // 将a[]按升序排列 int N = a.length; int h = 1; // 动态生成 h while (h < N/3) { h = 3 * h + 1; // 1, 4, 13, 40, 121... } while (h >= 1) { //将数组变为 h 有序 for (int i = h; i < N; i++) { // 将a[i]插入到a[i-h], a[i-2*h], a[]...之中 for (int j = i; j >= h && less(a[j], a[j-h]); j -= h) { exch(a, j, j-h); } } h = h / 3; } } // 比较元素大小 private static boolean less(Comparable v, Comparable w) { return v.compareTo(w) < 0; } // 将元素交换位置 private static void exch(Comparable[] a, int i, int j) { Comparable t = a[i]; a[i] = a[j]; a[j] = t; } // 在单行中打印数组 private static void show(Comparable[] a) { for (int i = 0; i < a.length; i++) { System.out.print(a[i] + " "); } System.out.println(); } // 测试数组元素是否有序 public static boolean isSorted(Comparable[] a) { for (int i = 1; i < a.length; i++) { if (less(a[i], a[i-1])) return false; } return true; } public static void main(String[] args) { // 读取字符串,将他们排序输出 Comparable[] a = StdIn.readAllStrings(); sort(a); assert isSorted(a); show(a); } }

     

    最新回复(0)