Algs4-2.2.23-2比较正文中实现的归并和反向复制辅助数组归并之间的性能
2.2.23改进。用实验评估正文中所提到的归并排序的三项改进(请见练习2.2.11)的效果,并比较正文中实现的归并和练习2.2.10所实现的归并之间的性能。根据经验给出应该在何时为子数组切换到插入排序。
2)比较正文中实现的归并和反向复制辅助数组归并之间的性能(练习2.2.10)
public class E2d2d23d2
{
public static double time (String alg,Double[] a)
{
Stopwatch timer =new Stopwatch();
if(alg.equals("Merge")) Merge.sort(a);
if(alg.equals("Merge2")) E2d2d10.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("Merge",N,T);
double t2=timeRandomInput("Merge2",N,T);
StdOut.printf("Merge spend time=%.2f Merge2 spendtime=%.2f Merge2/Merge rate=%.2f\n",t1,t2,t2/t1);
}
}
public class E2d2d10
{
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=hi;
for (int k=lo;k<=mid;k++)
aux[k]=a[k];
/*
//k 索引更容易理解的方式
for (int k=0;mid+1+k<=hi;k++)
aux[mid+1+k]=a[hi-k];
*/
for (int k=mid+1;k<=hi;k++)
aux[k]=a[hi-k+mid+1];
for(int k=lo;k<=hi;k++)
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(i,i-1)) return false;
return true;
}
}
import java.util.Arrays;
public class Merge
{
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;
}
}