import edu.princeton.cs.algs4.StdOut;
public class E2_1_27 {
public static void main(String[]args){
String alg1= "Shell";
String alg2= "Selection";
int N=128;
int T=100;
double prev1=SortCompare.timeRandomInput(alg1,N,T);//total for alg1
double prev2=SortCompare.timeRandomInput(alg2,N,T);//total for alg2
for (N=128*2;true;N+=N){
double now1=SortCompare.timeRandomInput(alg1,N,T);//total for alg1
double now2=SortCompare.timeRandomInput(alg2,N,T);//total for alg2
StdOut.printf("N=%8d shell's time=%7.4f ratio=%4.1f" +
" selection's time=%7.4f ratio=%4.1f\n",N,now1/T,now1/prev1,now2/T,now2/prev2 );
prev1=now1;
prev2=now2;
}
}
}
SortCompare的实现:
import edu.princeton.cs.algs4.*;
public class SortCompare {
public static void main(String[]args){
StdOut.print("Please input algorithm 1 name: ");
String alg1= StdIn.readString();
StdOut.print("\nPlease input algorithm 2 name: ");
String alg2=StdIn.readString();
StdOut.print("\nPlease input N: ");
int N=StdIn.readInt();
StdOut.print("\nPlease input times T: ");
int T=StdIn.readInt();
double t1=timeRandomInput(alg1,N,T);//total for alg1
double t2=timeRandomInput(alg2,N,T);//total for alg2
//StdOut.printf("For %d random Double\n\t %s is %.1f times faster than %s\n",N,alg1,t2/t1,alg2);
StdOut.printf("N=%d T=%d\n\talg1=%s time=%.1f\n\talg2=%s time=%.1f t1/t2=%.2f",N,T,alg1,t1,alg2,t2,t1/t2);
}
public static double time(String alg,Comparable[]a){
Stopwatch timer=new Stopwatch();
if (alg.toLowerCase().equals("Insertion".toLowerCase())) Insertion.sort(a);
if (alg.toLowerCase().equals("Selection".toLowerCase())) Selection.sort(a);
if (alg.toLowerCase().equals("Shell".toLowerCase())) Shell.sort(a);
return timer.elapsedTime();
}
public static double timeRandomInput(String alg,int N,int T){
//Use alg to sort T random arrays of length N.
double total=0.0;
Double[]a=new Double[N];
for (int t=0;t<T;t++){
//Perform one experiment(generate and sort an array).
for (int i=0;i<N;i++)
a[i]= StdRandom.uniform();
total+=time(alg,a);
}
return total;
}
}
结果: