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

前端 未结 7 2041
天命终不由人
天命终不由人 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:58

    Even though we set j = n * n at the beginning, we increment i and decrement j during each iteration, so shouldn't the resulting number of iterations be a lot less than n*n?

    Yes! That's why it's O(n^2). By the same logic, it's a lot less than n * n * n, which makes it O(n^3). It's even O(6^n), by similar logic.

    big-O gives you information about upper bounds.

    I believe you are trying to ask why the complexity is theta(n) or omega(n), but if you're just trying to understand what big-O is, you really need to understand that it gives upper bounds on functions first and foremost.

提交回复
热议问题