当j = i时对嵌套循环Big-O运行时感到困惑

时间:2019-01-26 00:51:54

标签: big-o

对于以下代码的“大哦”感到困惑:

iOS 5

是O(n ^ 2)吗?使我感到困惑的部分是j = i以及它将如何影响运行时。

2 个答案:

答案 0 :(得分:0)

是的,它是O((array.length)^ 2)。

  • 两个循环导致内部块的1/2 * n *(n + 1)个调用
  • 这相当于1/2 * n * n + 1/2 * n * 1。
  • 由于常量因子与O(n)表示法无关,因此您的代码恰好是O((array.length)^ 2)。

答案 1 :(得分:0)

假设 array.length n ,则内部循环的总执行量为:

round 1 (i=0) : n           this round j = 0 to n-1
round 2 (i=1) : n-1         this round j = 1 to n-1
   .
   .
   . 
round n (i=n-1) : 1         this round j = n-1 to n-1
--------------------------------
 Total :  n*(n+1)/2 is in O(n^2)
  

1+ 2+ ... + n = n(n + 1)/ 2    wikipedia link