运行时间双重for循环的复杂性 [英] Running time complexity of double for-loops
问题描述
我有些由以下算法混淆。特别是,我不明白为什么第一个是O(n),第二个是O(n ^ 2)。我的唯一的直觉也许是所述内环和外环的第一算法不是链。其次,我可以直观地看出,第二种算法是O(n ^ 2),但我们将如何去寻找一些常量C1,C2证明F(n)是大0小0的n ^ 2 <? / P>
总和= 0;
的for(int i = 0;我n种;我++)
为(诠释J = 0; J&n种; J ++)
综上所述++;
总和= 0;
的for(int i = 0;我n种;我++)
对于(INT J = 0; J&LT;我; J ++)
综上所述++;
。这都是为O(n 2 )
您code有一个便利的机制,用于测量的时间复杂度,那就是之
变量
去实现与不同的值 N
。如果你的之
S补充一条线,它是线性的。如果他们不它不是线性的。我想,你会发现,在你第一种算法,之
将永远是完全相同 N ^ 2
I'm somewhat confused by the following algorithms. In particular, I don't understand why the first is O(n) and the second is O(n^2). My only intuition is perhaps that the inner and outer loops for the first algorithm aren't "linked." Secondly, I can intuitively see that the second algorithm is O(n^2), but how would we go about finding some constants c1, c2 to prove f(n) is big-0 and little-0 of n^2?
sum = 0;
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++)
sum++;
sum = 0;
for (int i = 0; i < n; i++)
for (int j = 0; j < i; j++)
sum++;
Both of those are O(n2)
Your code has a handy mechanism for measuring the time complexity, and that is the sum
variable
Go implement that with different values for n
. if your sum
s make a line, it's linear. if they don't it's not linear. I think that you'll find that in your first algorithm, sum
will always be exactly n^2
这篇关于运行时间双重for循环的复杂性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!