标签:stdout not page assert show iss str oid fast
question:
Faster merge. Implement a version of merge() that copies the second half of a[] to aux[] in decreasing order and then does the merge back to a[]. This change allows you to remove the code to test that each of the halves kas been exhausted from the inner loop. Note: The resulting sort is not stable(see page 341).
answer:
//减少一个判断条件
import edu.princeton.cs.algs4.*; public class Merge { private static Comparable[] aux; public static void sort(Comparable[] a) { aux = new Comparable[a.length]; sort(a, 0, a.length-1); } private static boolean less(Comparable v, Comparable w) { return v.compareTo(w) < 0; } private static void show(Comparable[] a) { 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 merge(Comparable[] a, int lo, int mid, int hi) { int i = lo, j = hi;//注意这里j为hi int k; for(k = lo; k <= mid; k++)//复制前一半到aux里面 aux[k] = a[k]; for(int t = hi; t >= mid + 1;t--,k++)//复制后一半反向到aux里面 aux[k] = a[t]; for(int c = lo; c <= hi; c++)//把a[]填满就退出循环 { //减少了一个判断条件 //拿到边界时会出现aux[i] == aux[j],所以最后一次拿哪个都一样! if(less(aux[i], aux[j])) a[c] = aux[i++]; else a[c] = aux[j--]; } } private static void sort(Comparable[] a, int lo, int hi) { if(hi <= lo) return; int mid = lo + (hi - lo) / 2;//不用(a+b)/2是因为a+b可能超过int的上界,防止溢出 sort(a,lo,mid);//排左侧 sort(a,mid+1,hi);//排右侧 merge(a,lo,mid,hi);//归并 } public static void main(String[] args) { String[] a = In.readStrings(); sort(a); assert isSorted(a); show(a); } }
标签:stdout not page assert show iss str oid fast
原文地址:https://www.cnblogs.com/w-j-c/p/9119352.html