算法(Algorithms)第4版 练习 2.2.11(1)
实现关键代码:
private static void sort(Comparable[] input, int lo, int hi) { if((lo+CUTOFF-1) >= hi) { //use insertion sort for tiny subarrays insertionsort(input, lo, hi); return; } int mid = lo + (hi-lo)/2; sort(input, lo, mid); sort(input, mid+1, hi); merge(input, lo, mid, hi); }
整体:
package com.qiusongde; import edu.princeton.cs.algs4.In; import edu.princeton.cs.algs4.StdOut; public class MergeUseInsert { private static Comparable[] aux; private final static int CUTOFF = 8;//size public static void sort(Comparable[] input) { int N = input.length; aux = new Comparable[N]; sort(input, 0, N-1); } private static void sort(Comparable[] input, int lo, int hi) { if((lo+CUTOFF-1) >= hi) { //use insertion sort for tiny subarrays insertionsort(input, lo, hi); return; } int mid = lo + (hi-lo)/2; sort(input, lo, mid); sort(input, mid+1, hi); merge(input, lo, mid, hi); } private static void insertionsort(Comparable[] input, int lo, int hi) { for(int i = lo + 1; i <= hi; i++) { for(int j = i; j > lo && less(input[j], input[j-1]); j--) { exch(input, j, j-1); } } StdOut.printf("insertionsort(input, %4d, %4d)", lo, hi);//for test show(input);//for test } private static void exch(Comparable[] a, int i, int j) { Comparable t = a[i]; a[i] = a[j]; a[j] = t; } private static void merge(Comparable[] input, int lo, int mid, int hi) { //copy input[lo,hi] to aux[lo,hi] for(int i = lo; i <= hi; i++) { aux[i] = input[i]; } int i = lo; int j = mid + 1; for(int k = lo; k <= hi; k++) { if(i > mid) input[k] = aux[j++]; else if(j > hi) input[k] = aux[i++]; else if(less(aux[j], aux[i])) input[k] = aux[j++]; else input[k] = aux[i++]; } StdOut.printf("merge(input, %4d, %4d, %4d)", lo, mid, hi); show(input);//for test } private static boolean less(Comparable v, Comparable w) { return v.compareTo(w) < 0; } private static void show(Comparable[] a) { //print the array, on a single line. for(int i = 0; i < a.length; i++) { StdOut.print(a[i] + " "); } StdOut.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) { //Read strings from standard input, sort them, and print. String[] input = In.readStrings(); show(input);//for test sort(input); assert isSorted(input); show(input);//for test } }
验证:
M E R G E S O R T E X A M P L E insertionsort(input, 0, 7)E E G M O R R S T E X A M P L E insertionsort(input, 8, 15)E E G M O R R S A E E L M P T X merge(input, 0, 7, 15)A E E E E G L M M O P R R S T X A E E E E G L M M O P R R S T X
性能对比:
For 20000 random Doubles 1000 trials
Merge is 3.4s MergeFasterM is 3.1s MergeUseInsert is 3.0s