Algorithm Analysis¶
Definition
An algorithm is a finite set of instructions that, if followed, accomplishes a particular task. In addtion, all algorithms must satisfy the following criteria:
- Input (zero or more) and Output (at least one).
- Definiteness: clear and unambiguous.
- Finiteness: termination after finite number of steps.
- Effectiveness.
NOTE: A program does not have to be finite. e.g. an operating system.
Running Time¶
The most important resource to analyze is the running time. It consists of two parts
- Machine and Compiler-Dependent run times.
- Time and Space Complexities (Machine and Complier-Independent).
In FDS, we mainly consider the average time complexity \(T_\text{avg}(N)\) and the worst time complexity \(T_\text{worst}(N)\) as functions of input size \(N\).
Genernal Rules
- FOR LOOPS the statements inside the loop times the number of iterations.
- NESTED FOR LOOPS the statements multiplied by the product of the size.
- CONSECUTIVE STATEMENTS just add.
-
IF/ELSE running time of the test plus the larger of the running time of S1 and S2.
if (Condition) { S1; } else { S2; }
Asymptotic Notation¶
Definition
- \(T(N) = O(f(N))\) if there are positive constants \(c\) and \(n_0\) s.t.
- \(T(N) = \Omega(g(N))\) if there are positive constants \(c\) and \(n_0\) s.t.
- \(T(N) = \Theta(h(N))\) iff
- \(T(N) = o(p(N))\) if
Rules
-
If \(T_1(N) = O(f(N))\) and \(T_2(N) = O(g(N))\), then
\[ \begin{aligned} T_1(N) + T_2(N) &= \max(O(f(N)), O(g(N))), \\ T_1(N) \cdot T_2(N) &= O(f(N) \cdot g(N)). \\ \end{aligned} \] -
If \(T(N)\) is a polynomial of degree \(k\), then \(T(N) = \Theta(N^k)\).
Example
The recurrent equations for the time complexities of programs \(P1\) and \(P2\) are:
Find \(T(N)\) for \(P1\) and \(P2\) respectively.
Solution.
For \(P1\),
For \(P2\),
创建日期: 2023.01.04 01:26:14 CST