标签:compare trace main ring sso str sse less reads
question:
Show, in the style of the example trace with ALGORITHM 2.2, how insertion sort sorts the array E A S Y Q U E S T I O N.
answer:
import edu.princeton.cs.algs4.*; public class Insertion { public static void sort(Comparable[] a) { int N = a.length; for(int i = 0; i < N; i++) { int j; for(j = i; j > 0 && less(a[j], a[j-1]); j--) exch(a, j, j-1); StdOut.printf("%d %d\t", i, j); for(int t = 0; t < a.length; t++) StdOut.print(a[t] + " "); StdOut.println(); } } private static boolean less(Comparable v, Comparable w) { return v.compareTo(w) < 0; } private static void exch(Comparable[] a, int i, 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 Q U E S T I O N String[] a = In.readStrings();//CTRL + d sort(a); assert isSorted(a); show(a); } }
标签:compare trace main ring sso str sse less reads
原文地址:https://www.cnblogs.com/w-j-c/p/9105409.html