标签:OLE void 显示 归并 print block nbsp top span
question:
Give traces, in the style of the trace given with ALGORITHM 2.4, showing how the keys E A S Y Q U E S T I O N are sorted with top-down mergesort.
answer:
import edu.princeton.cs.algs4.*; public class Merge { private static Comparable[] aux; public static boolean less(Comparable v, Comparable w) { return v.compareTo(w) < 0; } public static void merge(Comparable[] a, int lo, int mid, int hi) { int i = lo; int j = mid + 1; for(int k = lo; k <= hi; k++) aux[k] = a[k]; 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++]; } } public static void sort(Comparable[] a) { aux = new Comparable[a.length]; sort(a, 0, a.length-1); } public static void sort(Comparable[] a, int lo, int hi) { if(hi<=lo) return; int mid = lo + (hi - lo)/2; sort(a,lo,mid); sort(a,mid+1,hi); merge(a,lo,mid,hi); show(a,lo,hi);//每次归并完后显示归并的元素 } public static void show(Comparable[] a, int lo, int hi) { for(int i = 0; i < lo; i++) { StdOut.print(" "); } for(int i = lo; i <= hi; i++) StdOut.print(a[i] + " "); StdOut.println(); } public static void main(String[] args) { //输入E A S Y Q U E S T I O N String[] a = In.readStrings(); sort(a); } }
标签:OLE void 显示 归并 print block nbsp top span
原文地址:https://www.cnblogs.com/w-j-c/p/9117383.html