标签:turn class import void down com otto else question
question:
Give the sequence of subarray sizes in the merges performed by both the top-down and the bottom-up mergesort algorithms, for N = 39.
answer:
//top-down
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(lo,hi); } public static void show(int lo, int hi) { StdOut.print(hi-lo+1 + " "); } public static void main(String[] args) { //输入一个N为39的string数组 //c a s e r t y w a w q c v b n m e t v m e q w r o p k l f g e x v r m n y i u String[] a = In.readStrings(); sort(a); } }
//bottom-up
import edu.princeton.cs.algs4.*; public class MergeBU { 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]; int N = a.length; for(int sz = 1; sz < N; sz+=sz) { for(int j = 0; j < N-sz; j+=2*sz) { merge(a,j,j+sz-1,Math.min(j+2*sz-1,N-1)); show(j,Math.min(j+2*sz-1,N-1)); } } } public static void show(int lo, int hi) { StdOut.print(hi-lo+1 + " "); } public static void main(String[] args) { //输入一个N为39的string数组 //c a s e r t y w a w q c v b n m e t v m e q w r o p k l f g e x v r m n y i u String[] a = In.readStrings(); sort(a); } }
标签:turn class import void down com otto else question
原文地址:https://www.cnblogs.com/w-j-c/p/9117713.html