简体   繁体   English

计算算法的T(n)时间复杂度

[英]Calculating T(n) Time Complexity of an Algorithm

I am looking for some clarification in working out the time efficiency of an Algorithm, specifically T(n). 我在寻找算法的时间效率,特别是T(n)时需要一些澄清。 The algorithm below is not as efficient as it could be, though it's a good example to learn from I believe. 尽管我认为这是一个很好的例子,但下面的算法并没有达到应有的效率。 I would appreciate a line-by-line confirmation of the sum of operations in the code: 我希望对代码中的操作总数进行逐行确认:

Pseudo-code 伪码

 1.  Input: array X of size n
 2.  Let A = an empty array of size n
 3.  For i = 0 to n-1
 4.      Let s = x[0]
 5.      For j = 0 to i
 6.          Let sum = sum + x[j]
 7.      End For
 8.      Let A[i] = sum / (i+1)
 9.  End For
 10. Output: Array A

My attempt at calculating T(n) 我尝试计算T(n)

 1.  1
 2.  n
 3.  n
 4.  n(2)
 5.  n(n-1)
 6.  n(5n)
 7.  -
 8.  n(6)
 9.  -
 10. 1

 T(n) = 1 + n + n + 2n + n^2 - n + 5n^2 + 6n + 1
      = 6n^2 + 9n + 2 

So, T(n) = 6n^2 + 9n + 2 is what I arrive at, from this I derive Big-O of O(n^2). 因此, T(n)= 6n ^ 2 + 9n + 2是我得出的结果,由此得出O(n ^ 2)的Big-O。 What errors, if any have I made in my calculation... 我在计算时犯了什么错误...

Edit: ...in counting the primitive operations to derive T(n)? 编辑:...在计算原始运算以得出T(n)时?

Your result O(n^2) is correct and is given by the two nested loops. 您的结果O(n ^ 2)是正确的,并且由两个嵌套循环给出。 I would prefer the derivation like 我更喜欢像

0 + 1 + 2 +  + (n-1) = (n-1)n/2 = O(n^2)

that follows from observing the nested loops. 从观察嵌套循环开始。

I'm not really sure on your methodology but O(n^2) does seem to be correct. 我不确定您的方法,但是O(n ^ 2)似乎是正确的。 At each iteration through the first loop you do a sub loop of the previous elements. 在第一个循环的每次迭代中,您都对前面的元素进行了子循环。 Therefore you're looking at 1 the first time 2 the second then 3 then... then n the final time. 因此,您第一次看的是1,第二看的是2,然后看的是3,然后……最后看的是n。 This is equivalent to the sum from 1 to n which gives you complexity of n^2. 这等效于从1到n的总和,使您的复杂度为n ^ 2。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM