Algs4-2.1.31双倍测试

本文介绍了一个用于测试排序算法性能的Java程序,通过双倍测试法评估了插入排序、选择排序和希尔排序的时间复杂度,验证了这些算法在随机输入情况下的运行时间特性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

转载于:https://www.cnblogs.com/longjin2018/p/9860058.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值