2.3.6编写一段代码来计算Cn的准确值,在N=100、1000和1000的情况下比较准确值和估计值2NlnN的差距。
public class E2d3d6
{
static int Cn=0;
public static void sort(Comparable[] a)
{
Cn=0;
StdRandom.shuffle(a);
sort(a,0,a.length-1);
StdOut.printf("N=%8d Cn=%8d 2NlnN=%8.0f
2NlnN/Cn=%2.1f
",a.length,Cn,2*a.length*Math.log(a.length),2*a.length*Math.log(a.length)/Cn);
}
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)
{ Cn++;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)
{
Double[] a=new Double[100];
Double[] b=new Double[1000];
Double[] c=new Double[10000];
Double[] d=new Double[100000];
Double[] e=new Double[1000000];
for(int i=0;i<a.length;i++)
a[i]=StdRandom.uniform();
for(int i=0;i<b.length;i++)
b[i]=StdRandom.uniform();
for(int i=0;i<c.length;i++)
c[i]=StdRandom.uniform();
for(int i=0;i<d.length;i++)
d[i]=StdRandom.uniform();
for(int i=0;i<e.length;i++)
e[i]=StdRandom.uniform();
sort(a);
sort(b);
sort(c);
sort(d);
sort(e);
}
}