Why is the Big-O complexity of this algorithm O(n^2)?

前端 未结 7 2046
天命终不由人
天命终不由人 2021-02-03 17:03

I know the big-O complexity of this algorithm is O(n^2), but I cannot understand why.

int sum = 0; 
int i = 1; j = n * n; 
while (i++ < j--) 
  s         


        
7条回答
  •  说谎
    说谎 (楼主)
    2021-02-03 17:50

    Yes, this algorithm is O(n^2).

    To calculate complexity, we have a table the complexities:

    O(1) O(log n) O(n) O(n log n)
    O(n²) O(n^a) O(a^n) O(n!)

    Each row represent a set of algorithms. A set of algorithms that is in O(1), too it is in O(n), and O(n^2), etc. But not at reverse. So, your algorithm realize n*n/2 sentences.

    O(n) < O(nlogn) < O(n*n/2) < O(n²)

    So, the set of algorithms that include the complexity of your algorithm, is O(n²), because O(n) and O(nlogn) are smaller.

    For example: To n = 100, sum = 5000. => 100 O(n) < 200 O(n·logn) < 5000 (n*n/2) < 10000(n^2)

    I'm sorry for my english.

提交回复
热议问题