条件语句的时间复杂性

时间:2016-06-22 10:40:21

标签: code-analysis

如何使用条件语句计算时间复杂度,这些条件语句可能会或可能不会导致更高的结果?

例如:

for(int i = 0; i < n; i++){  
   //an elementary operation   
   for(int j = 0; j < n; j++){
       //another elementary operation  
       if (i == j){  
           for(int k = 0; k < n; k++){
               //yet another elementary operation
           }
       } else {
           //elementary operation
       }
   }
}

如果if-else条件中的内容被颠倒了怎么办?

2 个答案:

答案 0 :(得分:0)

您的代码需要O(n ^ 2)。前两个循环采用O(n ^ 2)运算。 &#34; k&#34;循环执行O(n)操作并被调用n次。它给出O(n ^ 2)。代码的总复杂度为O(n ^ 2)+ O(n ^ 2)= O(n ^ 2)。

另一次尝试:

 - First 'i' loop runs n times.
 - Second 'j' loop runs n times. For each of is and js (there are n^2 combinations):
     - if i == j make n combinations. There are n possibilities that i==j, 
      so this part of code runs O(n^2).
     - if it's not, it makes elementary operation. There are n^2 - n combinations like that
       so it will take O(n^2) time.
 - The above proves, that this code will take O(n) operations.

答案 1 :(得分:-2)

这取决于您正在执行的分析类型。如果您正在分析worst-case complexity,那么请考虑两个分支的最差复杂性。如果您正在分析average-case complexity,则需要计算进入一个分支或另一个分支的概率,并将每个复杂度乘以获取该路径的概率。

如果更改分支,只需切换概率系数。