question:
Instrument shellsort to print the number of compares divided by rhe array size for each increment. Write a test client that tests the hypothesis that this number is a small constant, by sorting arrays of random Double values, using array size that are increasing powers of 10, starting at 100.
answer:
//我没有用10的幂,这样结果比较清楚
//我自认为自己是对的,要是有错误的话还请指出
import edu.princeton.cs.algs4.*; public class Shell { public static int sort(Comparable[] a)//返回比较次数 { int count = 0;//存比较次数 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++) { //网上有答案在这里加count++,但less才是比较啊,这里明显不是比较次数吧 for(int j = i; j >= h; j-=h)//比较后也不一定不交换,所以把循环拆开好看比较次数 { count++; if(less(a[j],a[j-h])) { exch(a,j,j-h); } else break; } } h = h/3; } return count; } 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) { int size = 100; int i = 2; while(i <= 40) { Double[] a = new Double[size + i * 100]; for(int j = 0; j < size + i *100; j++) a[j] = StdRandom.uniform(); int count = sort(a); double rate = (double)(size+i*100) / count; StdOut.println(rate); i++; } } }