1

I want to ask a question about time complexity.

Sum (array,n)
{
1.1 total_sum = 0;
1.2 for (i=0;i<n;i++)
1.2.1 total_sum = total_sum +array[i];
1.3 return total_sum;
}

the total steps for 1.2 statement is 2(n+1).. could anyone tell me that why it is 2(n+1) ?

4

1 回答 1

0

说,i=n-1。它增加,循环返回;再进行一次比较,这次它的计算结果为假(因为 i 现在等于 n)。总而言之,你运行这个 0, 1, ... ,n 次,每次执行两个操作 - 一起 2(n+1)。请注意,i++ 语句仅被计算 n 次,但在循环开始时您有一个额外的语句 (i=0)。

于 2012-10-11T17:26:36.587 回答