2.3.2
阿新 • • 發佈:2018-06-03
div import partition random span his AR answer shuffle
question:
Show, in the style of the quicksort trace given in this section, how quicksort sorts the array E A S Y Q U E S T I O N (for the purpose of this exercise, ignore the initial shuffle).
answer:
import edu.princeton.cs.algs4.*; public class Quicksort { 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; } public static int partition(Comparable[] a, int lo, int hi) { Comparable v = a[lo];//應該是a[lo]而不是a[0] inti = lo, j = hi + 1; while(true) { while(less(a[++i],v)) { if(i >= hi) break; } while(less(v,a[--j])) { if(j <= lo) break; }if(i >= j) break; exch(a,i,j); } exch(a,lo,j); if(lo == hi) StdOut.printf("%3d % 3d ", lo, hi); else StdOut.printf("%3d %3d % 3d ", lo, j, hi); show(a); return j; } public static void sort(Comparable[] a) { // StdRandom.shuffle(a); sort(a, 0, a.length-1); } public static void sort(Comparable[] a, int lo, int hi) { if(lo > hi) return; int mid = partition(a,lo,hi); sort(a,lo,mid-1); sort(a,mid+1,hi); } public static void show(Comparable[] a) { for(Comparable i: a) StdOut.print(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); StdOut.print(" "); show(a); } }
2.3.2