Algs4-2.2.26创建数组
2.2.26创建数组。使用SortCompare粗略比较在你的计算机上在merge()中和在sort()中创建aux[]的性能差异。
public class E2d2d26d3
{
public static double time (String alg,Double[] a)
{
Stopwatch timer =new Stopwatch();
if(alg.equals("merge")) E2d2d26d1.sort(a);
if(alg.equals("sort")) E2d2d26d2.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/T;
}//end timeRandomInput
public static void main(String[] args)
{
int N=Integer.parseInt(args[0]);
int T=Integer.parseInt(args[1]);
StdOut.printf("For %d random Doubles %d times sort\n",N,T);
double t1=timeRandomInput("sort",N,T);
double t2=timeRandomInput("merge",N,T);
StdOut.printf("aux in sort spend time=%.2f, in merge=%.2f,sort/time=%.2f \n",t1,t2,t1/t2);
}
}
public class E2d2d26d1
{
public static void sort(Comparable[] a)
{
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)
{
Comparable[] aux=new Comparable[hi-lo+1];
int i=lo,j=mid+1;
for (int k=lo;k<=hi;k++)
aux[k-lo]=a[k];
for(int k=lo;k<=hi;k++)
if (i>mid) {a[k]=aux[j-lo];j++;}
else if (j>hi) {a[k]=aux[i-lo];i++;}
else if (less(aux[j-lo],aux[i-lo])) {a[k]=aux[j-lo];j++;}
else {a[k]=aux[i-lo];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",isSorted(a));
}
}
public class E2d2d26d2
{
private static Comparable[] aux;
public static void sort(Comparable[] a)
{
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)
{
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)
{
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",isSorted(a));
}
}