How to calculate the worst analysis of this algorithm?

sum = 0;
for(int i = 0; i < N; i++)
    for(int j = i; j >= 0; j--)
       sum++;

From what I understand, the first line is 1 operation, the 2nd line is operations (i+1), the 3rd line is operations (i-1), and the 4th line is operations n. Does this mean that the time will be 1 + (i+1)(i-1) + n? These are just these last steps that confuse me.

+3
source share
6 answers

To analyze an algorithm that you don’t want to take turns, you ask: "How long does this particular line take?" The reason is that each line is not executed as many times. For example, the innermost line is executed a whole group of times, compared to the first line, which is run only once.

, , . , , " sum++?", , , , . , , . i == 0, ( 0 0). i == 1 ( j == 1, j == 0. , k- k + 1 times. ,

1 + 2 + 3 + ... + N

N (N + 1)      N^2 + N    N^2    N
---------   =  ------- =  --- + ---
    2             2        2     2

N^2 / 2 , , , O (N 2).

-, - , . , , , , . , . , , -O .

+6

.

sum++

, .

for(int j = i; j >= 0; j--)

+ 1 . , , , asm. , + 1. , + 1.

for(int i = 0; i < N; i++)

N . , , N. + 1, N (N + 1)/2 . ! , O (N 2).

+2

: . , O (n 2).

, , - "" . (, sum++ add sum to 1 giving temp; load temp to sum?). , , , O (n 2).

+1

; , . , "for", . , , "sum ++", N. Hint: .

?

, , "i". i? , ? (: , , ?)

, , .

? , N?

0

, , - ++ .

.

, :

Sigma (n) n 1 N.

: N*(N+1) / 2 - O(N^2)

, . , - N .

0

Sigma :

enter image description here

0

Source: https://habr.com/ru/post/1788742/


All Articles