算法分析

Analysis of Algorithms

学到这里才发现之前用 Big-Oh notation O(n)O(n) 描述时间复杂度是一个常见的误区......!

Mathematical Models

The total running time of an algorithm is the sum of cost ×\times frequency for all operations. In principle, we could always develop an accurate mathematical models for a particular algorithm.

However, taking exactly all operations into consideration seems too tedious.

Simplification 1: cost model

Cost model. Use some basic operations as a proxy for running time.

When a proper cost model is chosen, other operations could be ignored.

choose the operation with the highest frequency as the cost model

Simplification 2: tilde notation

We use tilde notation ∼\sim to estimate running time (or memory) as a function of input size NN. It will ignore all lower-order terms.

  • When NN is large, lower-order terms are negligible.
  • When NN is small, we simply don't care.

Technically, f(N)∼g(N)f(N)\sim g(N) means lim⁡N→∞f(N)g(N)=1\lim_{N\to\infty} \frac{f(N)}{g(N)}=1.

Order-of-Growth Classifications

Good news. the small set of functions 1,log⁡N,N,Nlog⁡N,N2,N31,\log N,N,N\log N,N^2,N^3 and 2N2^N suffices to describe order-of-growth of typical algorithms.

Here are the common order-of-growth classifications:

  • constant 11: statement
  • logarithmic log⁡N\log N: divide in half
  • linear NN: loop
  • linearithmic Nlog⁡NN\log N: divide and conquer
  • quadratic N2N^2: double loops
  • cubic N3N^3: triple loops
  • exponential 2N2^N: exhaustive search

Typically, better order of growth →\to faster in practice.

Commonly Used Notations

notation provides used to
Tilde ∼\sim leading term provide approximate model
Big Theta Θ(⋅)\Theta(\cdot) asymptotic growth rate classify algorithms
Big Oh O(⋅)O(\cdot) Θ(⋅)\Theta(\cdot) and smaller develop upper bounds
Big Omega Ω(⋅)\Omega(\cdot) Θ(⋅)\Theta(\cdot) and larger develop lower bounds

Common mistake. Interpreting big-Oh as an approximate model.

Example: 1-SUM problem == "Is there a 0 in the array?"

  • Upper bound. A specific algorithm.

    Brute-force algorithm for 1-SUM: Look at every array entry. Running time of the optimal algorithm for 1-SUM is O(N)O(N).

  • Lower bound. Proof that no algorithm can do better.

    Have to examine all NN entries (any unexamined one might be 00). Running time of the optimal algorithm for 1-SUM is Ω(N)\Omega(N).

If for a specific problem, upper bound O(N)=O(N)= lower bound Ω(N)\Omega(N), we say there exists an optimal algorithm with Θ(N)\Theta(N) running time.

Algorithm design aims to reduce the gap between upper bound O(N)O(N) and lower bound Ω(N)\Omega(N).

CC BY-NC-SA 4.0
正在加载评论…