提示:您可在线编辑运行本教程的实例 - 运行实例,去试试!
实现合并排序。
class Merge { private static Comparable[] compara; /** nowjava - 时 代 Java 提供 **/ private static boolean less(Comparable v, Comparable w) { return v.compareTo(w) < 0; } 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; } /**时 代 J a v a 公 众 号 - nowjava.com**/ private static void merge(Comparable[] a, Comparable[] aux, int lo, int mid, int hi) { // copy the array for (int k = lo; k <= hi; k++) aux[k] = a[k]; int i = lo, j = mid + 1; for (int k = lo; k <= hi; k++) { if (i > mid) a[k] = aux[j++]; else if (j > hi) a[k] = aux[i++]; else if (less(aux[j], aux[i])) a[k] = aux[j++]; else a[k] = aux[i++]; } } private static void sort(Comparable[] a, Comparable[] aux, int lo, int hi) { if (hi <= lo) return; int mid = lo + (hi - lo) / 2; // split the array in 2 parts sort(a, aux, lo, mid); // left sort(a, aux, mid + 1, hi); // right merge(a, aux, lo, mid, hi); } public static void sort(Comparable[] a) { compara = new Comparable[a.length]; sort(a, compara, 0, a.length - 1); }