1. 程式人生 > >Algs4-2.1.30幾何級數遞增序列

Algs4-2.1.30幾何級數遞增序列

top val -- ebp rabl pri -s main 運行

2.1.30幾何級數遞增序列。通過實驗找到一個t,使得對於大小為N=10^6的任意隨機數組,使用遞增序列1,下取整(t),下取整(t^2),
下取整(t^3),下取整(t^4),...的希爾排序的運行時間最短。給出你能找到的三個最佳t值以及相應的遞增序列。
t=5.31,遞增序列:28 149 795 4221 22416 119031 632056
t=5.39,遞增序列:29 156 844 4549 24520 132166 712377
t=4.01,遞增序列:16 64 258 1036 4157 16672 66858 268101
public class E2d1d30
{
public static void main(String[] args)
{
int[] SN=new int[20];
int h;
int i;
int maxSN=1000000;
int tLength=10000;
Double[][] tAndTime=new Double[tLength][2];
int indexOftAndTime=0;
//
int N=1000000;
int minValue=0;
int maxValue=1000000;
Integer[] a=new Integer[N];
Integer[] aCopy=new Integer[N];
for(int j=0;j<N;j++)
{
a[j]=StdRandom.uniform(minValue,maxValue);
aCopy[j]=a[j];
}
//
for(double t=3.3;t<10.0;t=t+0.01)
{
i=0;
h=1;
SN[i]=h;
i=1;
for(double k=2.0;k<10.0 && i<20;k++)
{
h=(int)Math.floor(Math.pow(t,k));
if (h<maxSN)
SN[i]=h;
else
break;
i++;
}//end for k
//
Stopwatch timer =new Stopwatch();
Shell2.sort(a,SN);
tAndTime[indexOftAndTime][0]=t;
tAndTime[indexOftAndTime][1]=timer.elapsedTime();
indexOftAndTime++;
//
for(int j=0;j<N;j++)
a[j]=aCopy[j];
}//end for t
//
for(int j=0;tAndTime[j][0]>0&&j<tLength;j++)
StdOut.printf("%f\t%f\n",tAndTime[j][0],tAndTime[j][1]);

}
}

public class Shell2
{
public static void sort(Comparable[] a,int[] SN)
{
int N=a.length;
int h;
for (int hIndex=SN.length-1;hIndex>0;hIndex--)
{
h=SN[hIndex];
for (int i=h;i<N;i++)
{
for (int j=i;j>=h && less(a[j],a[j-h]);j-=h)
exch(a,j,j-h);
}
}
}

private static boolean less(Comparable v,Comparable w)
{ 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=0;i<a.length;i++)
if(less(a[i],a[i-1])) return false;
return true;
}
}

Algs4-2.1.30幾何級數遞增序列