数据结构与算法分析 C 语言描述第二版第二章 时间复杂度计算

数据结构与算法分析 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:

  1. line 3: the declarations count for no time.
  2. line 4 and 7: count for one unit each.
  3. 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.
  4. line 5: has a hidden costs of initializing i i , testing i < = N i <= N , and increasing i i . 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 O ( N ) O(N) .

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 T 1 ( N ) = O ( f ( N ) ) a n d T 2 ( N ) = O ( g ( N ) ) , t h e n : T_1(N) = O(f(N)) and T_2(N) = O(g(N)), then:

(a) T 1 ( N ) + T 2 ( N ) = m a x ( O ( f ( N ) ) , O ( g ( N ) ) ) T_1(N) + T_2(N) = max(O(f(N)), O(g(N)))

(b) T 1 ( N ) T 2 ( N ) = O ( f ( N ) ) O ( g ( N ) ) T_1(N) * T_2(N) = O(f(N)) * O(g(N))

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 S 1 S1 and S 2 S2 .

发布了120 篇原创文章 · 获赞 2 · 访问量 5801

猜你喜欢

转载自blog.csdn.net/Lee567/article/details/103271139