2.1.9
阿新 • • 發佈:2018-05-29
amp shells print AC with ngs stat XA int
question:
Show, in the style of the example trace with ALGORITHM 2.3, how shellsort sorts the array E A S Y S H E L L S O R T Q U E S T I O N.
answer:
import edu.princeton.cs.algs4.*; public class Shell { public static void sort(Comparable[] a) { int N = a.length; int h = 1;while(h < N/3) h = 3*h + 1; while(h>=1) { for(int i = h; i < N; i++) { for(int j = i; j >= h && less(a[j],a[j-h]); j-=h) exch(a,j,j-h); } StdOut.print(h + "-sort\t"); for(int t = 0; t < a.length; t++) StdOut.print(a[t] + " "); StdOut.println(); h = h/3; } } private static boolean less(Comparable v, Comparable w) { return v.compareTo(w) < 0; } private static void exch(Comparable[] a, inti, int j) { Comparable t = a[i]; a[i] = a[j]; a[j] = t; } 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 main(String[] args) { //輸入E A S Y S H E L L S O R T Q U E S T I O N String[] a = In.readStrings();//CTRL + d sort(a); assert isSorted(a); show(a); } }
2.1.9