简体   繁体   English

如何计算这个基本求和算法的时间复杂度?

[英]How to calculate the time complexity of this basic summing algorithm?

I want to understand what and how to calculate the time complexity of this algorithm given in pseudocode below.我想了解以下伪代码中给出的算法的时间复杂度是什么以及如何计算。 I suspect the TC is O(n) since there is a loop iterating through the entire list but I'm not sure or is it O(n^2) since in every loop the search function of lists is also called?我怀疑 TC 是 O(n) 因为有一个循环遍历整个列表但我不确定还是 O(n^2) 因为在每个循环中列表的search功能也被调用? But also generally how to calculate time complexities of given algorithms.但一般来说如何计算给定算法的时间复杂度。 Thank you in advance.先感谢您。

for i = 0 to n-1
    Add the numbers A[0] thru A[i]
    Store the result in B[i]

The running time of the algorithm you have is O(n^2).您拥有的算法的运行时间是 O(n^2)。 In the second line you are summing A[0] to A[i].在第二行中,您将 A[0] 与 A[i] 相加。 So the loop iterates n times.所以循环迭代 n 次。 In the first iteration you are adding A[0], then A[0] + A[1], then A[0] + A[1] + A[2] and so on.在第一次迭代中,您将添加 A[0],然后是 A[0] + A[1],然后是 A[0] + A[1] + A[2],依此类推。

So in general on iteration i you are adding i numbers.所以一般来说,在迭代 i 中,您将添加 i 个数字。 So the running time would be:所以运行时间将是:

1 + 2 + 3 + ... + n

This is the sum of the first n numbers which evaluates to n(n+1)/2 : https://brilliant.org/wiki/sum-of-n-n2-or-n3/这是评估为n(n+1)/2的前 n 个数字的总和: https : //brilliant.org/wiki/sum-of-n-n2-or-n3/

In general, not every line inside a loop is constant time.通常,并非循环内的每一行都是恒定时间。 Try to look at what happens for each line at a few different iterations of the loop to get an idea of what is going on.尝试查看在循环的几次不同迭代中每一行发生了什么,以了解发生了什么。 If it changes in each iteration then it is not constant.如果它在每次迭代中都发生变化,那么它就不是恒定的。

There is however an O(n) algorithm where you simply increment a sum variable:然而,有一个 O(n) 算法,您只需增加一个 sum 变量:

sum = 0
for i = 0 to n - 1:
    sum += A[i]
    B[i] = sum

In this case, at the start of iteration i, sum already stores the sum of A[0] to A[i-1] so to get the sum of A[0] to A[i] simply add A[i]在这种情况下,在迭代 i 开始时,sum 已经存储了 A[0] 到 A[i-1] 的总和,因此要获得 A[0] 到 A[i] 的总和,只需添加 A[i]

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

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