数据结构与算法分析 C 语言描述第二版第二章 时间复杂度计算
1. A Simple Example
int Sum(int N)
{
int i, PartialSum;
PartialSum = 0;
for (i = 1; i <= N; i++)
PartialSum += i * i * i;
return PartialSum;
}
Analysis if the running time:
- line 3: the declarations count for no time.
- line 4 and 7: count for one unit each.
- line 6: counts for four units per time executed(two for multiplication, one addition, and one assignment) and is executed N times, for a total of 4N units.
- line 5: has a hidden costs of initializing , testing , and increasing . The total cost of all these is 1 to initialize, N+1 for all the tests, and N for all the increments, which is 2N+2.
We ignore the costs of calling function and returning, for a total of 6N+4.
Thus, we say this function is .
2. General Rules
RULE 1 FOR LOOPS
The running time of a for loop is at most the running time of the statements inside the for loop (including tests) times the number of iterations.
RULE 2 NESTED FOR LOOPS
Analyze these inside out. The total running tome of a statement inside a group of nested loops is the running time if the statement multiplied by the product of the size of all for loops.
RULE 3 CONSECUTIVE STATEMENTS
These just add (which means that the maximum is the one that counts).
If
(a)
(b)
RULE 4 IF/ELSE
if (condition)
S1;
else
S2;
The running time of an if/else statement is never more than the running time if the test plus the larger of the running times of and .