time()
实现算法之后,下一步我们要确定一个输入模型.对于排序,在上一节里我们采用的是简单的输入的自然数组,然而要想比较两种算法的性能,我们需要更为复杂的模型.
为了比较,我们采用SortCompare类来做几次实验,使用Stopwatch来计时,下面的time()函数的任务是调用本章节中的几种常用的排序算法.
SortCompare
public class SortCompare {
public static void main(String[] args) {
String alg1 = args[0];
String alg2 = args[1];
int N = Integer.parseInt(args[2]);
int T = Integer.parseInt(args[3]);
double t1 = timeRandomInput(alg1, N, T);
double t2 = timeRandomInput(alg2, N, T);
System.out.print("For " + N + " random Doubles\n " + alg1 + " is");
System.out.print(t2 / t1 + " times faster than " + alg2 + "\n");
}
public static long time(String alg, int[] A) {
long start = System.currentTimeMillis();
if (alg.equals("Insertion"))
Insertion.sort(A);
if (alg.equals("Selection"))
Selection.sort(A);
if (alg.equals("Bubble"))
Bubble.sort(A);
long end = System.currentTimeMillis();
return end - start; //返回timer经过的时间
}
public static double
timeRandomInput(String alg, int N,
int T) { //使用算法alg将T个长度为N的数组排序
long total = 0.0;
Double A[] = new Double[N];
for (int t = 0; t < T; t++) { //进行一个测试,生成一个数组并且排序
for (int i = 0; i < A.length; i++) {
A[i] = StdRandom.uniform();
}
total += time(alg, A);
}
return total;
}
}