Algs4-2.3.31运行时间直方图

2.3.31运行时间直方图。编写一个程序,接受命令行参数N和T,用快速排序对大小为N的随机浮点数数组进行T次排序,并将所有运行时间绘制成直方图。令N=10^3、10^4、10^5和10^6,为了使曲线更平滑,T值越大越好。这个练习最关键的地方在于找到适当的比例绘制出实码结果。
1)1000时
图片
2)10000时
图片
3)100000时
图片
4)1000000时
图片

import java.awt.Color;
public class E2d3d31
{
    public static void sort(Comparable[] a)
    {
      StdRandom.shuffle(a);
      sort(a,0,a.length-1);
    }
   
    private static void sort(Comparable[] a,int lo,int hi)
    {
        if (hi<=lo) return;
        int j=partition(a,lo,hi);
   
        sort(a,lo,j-1);
        sort(a,j+1,hi);
    }
 
    private static int partition(Comparable[] a,int lo,int hi)
    {
        int i=lo,j=hi+1;
        Comparable v=a[lo];
        while(true)
        {
            while(less(a[++i],v)) if(i==hi) break;
            while(less(v,a[--j])) if(j==lo) break;
          
            if(i>=j) break;
            exch(a,i,j);
        }
        exch(a,lo,j);
        return j;
    }
   

   
    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 N=Integer.parseInt(args[0]);
        int T=Integer.parseInt(args[1]);
        //
        StdDraw.setXscale(0,T);
        StdDraw.setYscale(0,1);
        StdDraw.setPenColor(Color.RED);
        //
        for(int i=0;i<T;i++)
        {
        Double[] a=new Double[N];
        for(int j=0;j<N;j++)
            a[j]=StdRandom.random();
         Stopwatch timer=new Stopwatch();
         sort(a);
         StdDraw.filledRectangle(1.0*i,0.0,0.5,timer.elapsedTime()/10);
        }
    }
}

原文地址:https://www.cnblogs.com/longjin2018/p/9868594.html