What's the complexity of for i: for o = i+1

前端 未结 4 1283
难免孤独
难免孤独 2020-12-22 06:52
for i = 0 to size(arr)
   for o = i + 1 to size(arr)
      do stuff here

What\'s the worst-time complexity of this? It\'s not N^2, because the seco

相关标签:
4条回答
  • 2020-12-22 07:29

    When you want to determine the complexity class of an algorithm, all you need is to find the fastest growing term in the complexity function of the algorithm. For example, if you have complexity function f(n)=n^2-10000*n+400, to find O(f(n)), you just have to find the "strongest" term in the function. Why? Because for n big enough, only that term dictates the behavior of the entire function. Having said that, it is easy to see that both f1(n)=n^2-n-4 and f2(n)=n^2 are in O(n^2). However, they, for the same input size n, don't run for the same amount of time.

    In your algorithm, if n=size(arr), the do stuff here code will run f(n)=n+(n-1)+(n-2)+...+2+1 times. It is easy to see that f(n) represents a sum of an arithmetic series, which means f(n)=n*(n+1)/2, i.e. f(n)=0.5*n^2+0.5*n. If we assume that do stuff here is O(1), then your algorithm has O(n^2) complexity.

    for i = 0 to size(arr)

    I assumed that the loop ends when i becomes greater than size(arr), not equal to. However, if the latter is the case, than f(n)=0.5*n^2-0.5*n, and it is still in O(n^2). Remember that O(1),O(n),0(n^2),... are complexity classes, and that complexity functions of algorithms are functions that describe, for the input size n, how many steps there is in the algorithm.

    0 讨论(0)
  • 2020-12-22 07:35

    It is N ^ 2, since it's the product of two linear complexities.

    (There's a reason asymptotic complexity is called asymptotic and not identical...)

    See Wikipedia's explanation on the simplifications made.

    0 讨论(0)
  • 2020-12-22 07:35

    It's n*(n-1)/2 which is equal to O(n^2).

    0 讨论(0)
  • 2020-12-22 07:41

    Think of it like you are working with a n x n matrix. You are approximately working on half of the elements in the matrix, but O(n^2/2) is the same as O(n^2).

    0 讨论(0)
提交回复
热议问题