1. 程式人生 > >Algs4-2.1.31雙倍測試

Algs4-2.1.31雙倍測試

規模 選擇排序 input ota 猜想 quick bsp als his

2.1.31雙倍測試。編寫一個能夠對排序算法進行雙倍測試的用例。數組規模N的起始值為1000,排序後打印N、估計排序用時、實際排序用時以及在N增倍之後兩次用時的比例。用這段程序驗證在隨機輸入模型下插入排序和選擇排序的運行時間都是平方級別的。對希爾排序的性能作出猜想並驗證你的猜想。
技術分享圖片
public class SortCompare
{
public static double time (String alg,Double[] a)
{
Stopwatch timer =new Stopwatch();
if(alg.equals("Insertion")) Insertion.sort(a);
if(alg.equals("Selection")) Selection.sort(a);
if(alg.equals("Shell")) Shell.sort(a);
// if(alg.equals("Merge")) Merge.sort(a);
// if(alg.equals("Quick")) Quick.sort(a);
// if(alg.equals("Heap")) Heap.sort(a);
return timer.elapsedTime();
}

public static double timeRandomInput(String alg,int N,int T)
{
double total =0.0;
Double[] a=new Double[N];
for (int t=0;t<T;t++)
{
for (int i=0;i<N;i++)
a[i]=StdRandom.uniform();
total+=time(alg,a);
}
return total;
}//end timeRandomInput



public static void main(String[] args)
{
/*
String alg1=args[0];
String alg2=args[1];
int N=Integer.parseInt(args[2]);
int T=Integer.parseInt(args[3]);
double t1=timeRandomInput(alg1,N,T);
double t2=timeRandomInput(alg2,N,T);
StdOut.printf("For %d random Doubles\n %s is",N,alg1);
StdOut.printf(" %.2f times faster than %s\n",t2/t1,alg2);
*/
double prevT1=0.0;
double prevT2=0.0;
double prevT3=0.0;
double thisT1=0.0;
double thisT2=0.0;
double thisT3=0.0;
for (int N=1000;N<1000000000;N=2*N)
{
prevT1=thisT1;
prevT2=thisT2;
prevT3=thisT3;
//
thisT1=timeRandomInput("Insertion",N,1);
thisT2=timeRandomInput("Selection",N,1);
thisT3=timeRandomInput("Shell",N,1);
//
StdOut.printf("---For %d random Doubles\n",N);
StdOut.printf("Insertion use time=%.2f ,tihisTime/prevTime=%.2f\n",thisT1,thisT1/prevT1);
StdOut.printf("Selection use time=%.2f ,tihisTime/prevTime=%.2f\n",thisT2,thisT2/prevT2);
StdOut.printf("Shell use time=%.2f ,tihisTime/prevTime=%.2f\n",thisT3,thisT3/prevT3);
}
}
}

Algs4-2.1.31雙倍測試