Once An algorithm are given for a problemand decided to being correct, an important step is To determine how much in the Resources,such as time or space, the algorithm would require.
The important things to know is:
1) It ' s very bad style to include constants or low-order terms inside a Big-oh
2) This means, in any analysis, that ignore lower-order terms and constants.
Example:do not say T (n) = O (2n^2) or t (n) = O (n^2 + N);
The correct form is T (N) = O (n^2).
General Rules:
rule1:for Loop:
The running time of a For loop are at the running time of the statements inside the for loop (including tests) times th E Number of iterations.
As an example, the following program fragment is O (N):
for (i=0; i<n; i++) k++;
rule2:nested for Loop:
Analyze these inside out. The total running time of a statement inside a group of nested loops are the running time of the statement multiplied by th E Product of the sizes of the for loops.
As an example, the following program fragment is O (n^2):
for (i=0; i<n; i++) for (j=0; j<n; j + +) k++;
rule3:consecutive Statements:
These just add (which means that the maximum are the one that counts).
As an example, the following program fragment, which have O (N) work followed by O (n^2) work, is also O (n^2):
For (i=0, i<n; i++) a[i] = 0;for (i=0; i<n; i++) for (j=0; j<n; j + +) A[i] + = a[j]+i+j;
Rule4:if/else:
for the Fragment
if (Condition)
S1
Else
S2
The running time of an if/else statement was never more than the running time of the test plus the larger of the running TI Mes of S1 and S2.
Notices:
A basic strategy of analyzing from the inside (or deepest part) to our works.
If There is function calls, these must be analyzed first.
Reference:
Data Structures and algorithm analysis in C. Second edtion
Than for reading!
--by Lzq at Nanyang may.26.2014