Algs4-2.2.27子数组长度
2.2.27子数组长度。用归并将大型随机数组排序,根据经验用N(某次归并时两个子数组的长度之和)的函数估计当一个子数组用尽时另一个子数组的平均长度。
public class E2d2d27
{
private static Comparable[] aux;
public static long sumN,subN;
public static void sort(Comparable[] a)
{
sumN=0;
subN=0;
aux=new Comparable[a.length];
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);
merge(a,lo,mid,hi);
}
public static void merge(Comparable[] a,int lo,int mid,int hi)
{
sumN=sumN+(hi-lo+1);
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++];subN++;}
else if (j>hi) {a[k]=aux[i++];subN++;}
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)
{
Integer N=Integer.parseInt(args[0]);
Comparable[] a=new Comparable[N];
for(int i=0;i<N;i++)
a[i]=StdRandom.uniform();
sort(a);
StdOut.printf("isSorted=%s,N=%d,subN=%d,subN/N=%.4f\n",isSorted(a),sumN,subN,1.0*subN/sumN);
}
}
public class E2d2d27
{
private static Comparable[] aux;
public static long sumN,subN;
public static void sort(Comparable[] a)
{
sumN=0;
subN=0;
aux=new Comparable[a.length];
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);
merge(a,lo,mid,hi);
}
public static void merge(Comparable[] a,int lo,int mid,int hi)
{
sumN=sumN+(hi-lo+1);
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++];subN++;}
else if (j>hi) {a[k]=aux[i++];subN++;}
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)
{
Integer N=Integer.parseInt(args[0]);
Comparable[] a=new Comparable[N];
for(int i=0;i<N;i++)
a[i]=StdRandom.uniform();
sort(a);
StdOut.printf("isSorted=%s,N=%d,subN=%d,subN/N=%.4f\n",isSorted(a),sumN,subN,1.0*subN/sumN);
}
}