Algs4-2.2.24-改进的有序测试

 2.2.24改进的有序测试。在实现中用大型随机数组评估练习2.2.8所做的修改的效果。根据经验用N(被排序的原始数组的大小)的函数描述条件语句(a[mid]<=a[mid+1])成立(无论数组是否有序)的平均次数。
约:0.288N。
public class E2d2d24
{
    private static Comparable[] aux;
    public static int orderTimes=0;
   
    public static void sort(Comparable[] a)
    {
        aux=new Comparable[a.length];
        orderTimes=0;
        sort(a,0,a.length-1);
    }
   
    public static void sort(Comparable[] a,int lo,int hi)
    {
        if (hi<=lo) return;
        int mid=lo+(hi-lo)/2;
        sort(a,lo,mid);
        sort(a,mid+1,hi);
        if(!less(a[mid+1],a[mid])){orderTimes++; return;}
        merge(a,lo,mid,hi);
    }

   
    public static void merge(Comparable[] a,int lo,int mid,int hi)
    {
        int i=lo,j=mid+1;
        for (int k=lo;k<=hi;k++)
        aux[k]=a[k];
       
        for(int k=lo;k<=hi;k++)
        if        (i>mid) a[k]=aux[j++];
        else if (j>hi)    a[k]=aux[i++];
        else if (less(aux[j],aux[i])) a[k]=aux[j++];
        else            a[k]=aux[i++];
      }
    private static boolean less(Comparable v,Comparable w)
    { return v.compareTo(w)<0;}

     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]);
        
         long sumOrderTimes=0;
         Comparable[] a=new Comparable[N];
         for(int t=1;t<=T;t++)
         {
             for(int i=0;i<N;i++)
                 a[i]=StdRandom.uniform();
             //
             sort(a);
             sumOrderTimes=sumOrderTimes+orderTimes;
             StdOut.printf("N=%d T=%-5d orderTimes=%d avgOrderTimesRate/N=%.4f\n",N,t,orderTimes,sumOrderTimes*1.0/N/t);
         }
     }
}

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