这个嵌套循环的算法复杂度
Algorithmic complexity of this nested loop
是下面代码的O(n)
还是O(n*logn)
:
for(int j=n, int sum = 0; j>0 ; j--)
for(int k=j; k >0; k--) sum++;
迭代列表:
j = 5: k = 5, 4, 3, 2, 1
j = 4: k = 4, 3, 2, 1,
j = 3: k = 3, 2, 1
j = 2: k = 2, 1
j = 1: k = 1
我们总共进行了 15 次迭代。
但是,如果是O(n)
,那么只能迭代5次。
如果是 O(n*logn)
,答案将只有大约 11-12 次迭代。
是O(n^2)
。为什么?那么它需要:
看,n = 5
的计算次数实际上是 15。另一方面,对于 n=100
,它将是 5050。这与 100log100
相差 460 左右。
根据维基百科:
Big O notation is a mathematical notation that describes the limiting behavior of a function when the argument tends towards a particular value or infinity. It is a member of a family of notations invented by Paul Bachmann, Edmund Landau, and others, collectively called Bachmann-Landau notation or asymptotic notation.
是下面代码的O(n)
还是O(n*logn)
:
for(int j=n, int sum = 0; j>0 ; j--)
for(int k=j; k >0; k--) sum++;
迭代列表:
j = 5: k = 5, 4, 3, 2, 1
j = 4: k = 4, 3, 2, 1,
j = 3: k = 3, 2, 1
j = 2: k = 2, 1
j = 1: k = 1
我们总共进行了 15 次迭代。
但是,如果是O(n)
,那么只能迭代5次。
如果是 O(n*logn)
,答案将只有大约 11-12 次迭代。
是O(n^2)
。为什么?那么它需要:
看,n = 5
的计算次数实际上是 15。另一方面,对于 n=100
,它将是 5050。这与 100log100
相差 460 左右。
根据维基百科:
Big O notation is a mathematical notation that describes the limiting behavior of a function when the argument tends towards a particular value or infinity. It is a member of a family of notations invented by Paul Bachmann, Edmund Landau, and others, collectively called Bachmann-Landau notation or asymptotic notation.