Algs4-2.1.31双倍测试

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);
        }
    }
}

posted @ 2018-10-27 08:58  修电脑的龙生  阅读(271)  评论(0编辑  收藏  举报