普林斯顿算法课Part 1 Week 1 Analysis of Algorithms

这一课讲的是如何预测算法的性能及比较不同的算法。
这里写图片描述

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×1010×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 )
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值