这一课讲的是如何预测算法的性能及比较不同的算法。
1. Observations
例子:3-SUM
给定N个不同的integer,取三个相加之和为0的有多少种组合。
% more 8ints.txt
8
30 -40 -20 -10 40 0 10 5
% java ThreeSum 8ints.txt
4
存在如下几种组合:
30 -40 10
30 -20 -10
-40 40 0
-10 0 10
1.1 3-SUM: brute-force algorithm
public class ThreeSum
{
public static int count(int[] a)
{
int N = a.length;
int count = 0;
for (int i = 0; i < N; i++)
for (int j = i+1; j < N; j++)
for (int k = j+1; k < N; k++)
if (a[i] + a[j] + a[k] == 0)
count++;
return count;
}
public static void main(String[] args)
{
int[] a = In.readInts(args[0]);
StdOut.println(count(a));
}
}
1.2 度量运行时间
public static void main(String[] args)
{
int[] a = In.readInts(args[0]);
Stopwatch stopwatch = new Stopwatch();
StdOut.println(ThreeSum.count(a));
double time = stopwatch.elapsedTime();
}
1.3 经验分析:记录不同输入大小所耗时间
N | time (seconds) |
---|---|
250 | 0.0 |
500 | 0.0 |
1,000 | 0.1 |
2,000 | 0.8 |
4,000 | 6.4 |
8,000 | 51.1 |
16,000 | ? |
运行时间与输入大小之间的关系
由此得到 T(N)=1.006×10–10×N2.999 T ( N ) = 1.006 × 10 – 10 × N 2.999
1.4 Doubling hypothesis:快速估计指数b的方法
N | time (seconds) | ratio | lg ratio |
---|---|---|---|
250 | 0.0 | – | |
500 | 0.0 | 4.8 | 2.3 |
1,000 | 0.1 | 6.9 | 2.8 |
2,000 | 0.8 | 7.7 | 2.9 |
4,000 | 6.4 | 8.0 | 3.0 |
8,000 | 51.1 | 8.0 | 3.0 |
T(2N)T(N)=a(2N)baNb=2b T ( 2 N ) T ( N ) = a ( 2 N )