简体   繁体   English

嵌套循环的复杂性

[英]Nested loops complexity

I've this C# method: 我有这个C#方法:

private void Process()
{

  foreach (Vat vat in vats) // n elements
  {
    foreach (ProcessResultRow row in processResultRows) // m elements
    {
      // something here
    }

    foreach (KeyValuePair<int, Shop> entry in _shopsList) // j elements
    {
      // something else here
    }
  }

}

I know two nested loops have a O(n^2) complexity. 我知道两个嵌套循环的复杂度为O(n^2) Is it right in this example? 在这个例子中对吗?

I am undecided because of the fact that within the external cycle I have two for cicles at the same level. 我不确定,因为在外部循环中,我有两个相同水平的冰柱。

Prividing that loops don't have return , break and alike (eg throwing exception) the compleixity is 认为循环没有returnbreak和类似内容(例如,引发异常),则复杂性是

O(n * (m + j)) == O(n * m) + O(n * j)

if both m and j are constants we have 如果mj都是常数

O(n*m + n*j) == m * O(n) + j * O(n) == O(n)  

if at least one m or j such that m ~ n or j ~ n then we have 如果至少一个mj使得m ~ nj ~ n那么我们有

// here m ~ n and j is some const
O(n * m) + O(n * j) == O(n * n) + j * O(n) == O(n**2) + O(n) == O(n**2)

As @RobinBennet said, the answer is O(n * (m + j)) . 正如@RobinBennet所说,答案是O(n * (m + j))

The outer loop iterates n times (one for each element). 外循环迭代n次(每个元素一个)。 For each element within the outer loops, the first inner loop iterates m times and the second j times - so for each element you perform O(m + j) steps. 对于外部循环中的每个元素,第一个内部循环重复m次,第二个j次-因此,对于每个元素,您都执行O(m + j)步骤。 Iterate over n elements, O(n * (m + j). 迭代n个元素O(n *(m + j)。

That is, assuming that m, j are not related to n - if, for example m = j = n, you'd get O(n^2) 也就是说,假设m,j与n不相关-例如,如果m = j = n,则得到O(n ^ 2)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM