简体   繁体   中英

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? 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). In the second line you are summing A[0] to A[i]. So the loop iterates n times. In the first iteration you are adding A[0], then A[0] + A[1], then A[0] + A[1] + A[2] and so on.

So in general on iteration i you are adding i numbers. 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/

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:

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]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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