此伪代码的时间复杂度是多少?

时间:2020-06-21 11:29:06

标签: algorithm performance time-complexity pseudocode

我没有很多知识可以计算复杂性。您能帮助估计以下伪代码的复杂性吗?

算法1:

Input: V1, V2 and V3 and another vector C// Vectors of size n
Output: response..
V_f = f(V1, V2, 3) // function performs simple multiplication and additions on the vector
for i in range(0,n) // loop over element in the vector
     if V_f(i) != C(i) 
              // sort the V1(i), V2(i) and V3(i) and retrieve the middle value
              // if the middle value is in a range of certain values then launch Algorithm 2  
             // Over the result of Algorithm 2 (using if expressions), print the response
// end and return result

算法2

Input: Sorted

 Values C{1}, C{2} and C{3} and the vector C

Output: Response:

for i in range (o,n) // loop over the elements 
       // According to the values of C and C{i}, perform additions (using if expressions)
// end and return result

循环内的操作只是加法或简单测试。另外,算法2与Algorithm1一起执行,这意味着我在一个循环内有一个循环(对吗?):

for i in range (n)
// operations
// for j in range (n)
// operations

那么这是否意味着该算法的时间复杂度为O(n^2)?其中n是向量的大小?

还有一个普遍的问题,如果并行执行算法1和算法2,总体复杂度是多少?是每种算法的复杂度之和还是最大值?

1 个答案:

答案 0 :(得分:1)

算法1

  1. algorithm1将首先对向量执行简单的乘法和加法。假设它在每个向量上从头到尾循环并执行一些计算,则迭代次数将为3*N ,这将被视为O(N)

    V_f = f(V1, V2, 3)          #Time complexity will be O(N)
    
  2. 第一个算法中的下一条语句也将从0 to N开始循环。假设在每种情况下V_f(i) != C(i),您都必须对V1[i]V2[i]V3[i]进行排序,这将花费恒定的O(1)时间。

    for i in range(0,n) // loop over element in the vector
        if V_f(i) != C(i) 
    

    在下一条语句中,您要检查的是上述已排序元素的中间值是否在特定范围内-// if the middle value is in a range of certain values then launch Algorithm 2 ,因此,此操作的时间复杂度取决于检查的方式以及范围的大小。我将假设您需要检查从ab的连续范围,因此此步骤仅需执行O(1)。现在将调用Algorithm2。

算法2

  1. 算法2-

     for i in range (o,n) // loop over the elements 
            // According to the values of C and C{i}, perform additions (using if expressions)
     // end and return result
    

    在这里,您将再次从0 to N开始循环,并在每次迭代中执行一些计算,这些计算将花费O(1)。因此,整个算法的总时间复杂度为O(N)


那么这是否意味着该算法的时间复杂度为O(n ^ 2)?

现在,假设情况最糟,您将必须在 algorthm1循环中的每次迭代。因此,如您所说,时间复杂度将为O(N^2)。请注意,这还取决于计算的简单程度,在某些值范围内进行检查的方式,以及最终时间复杂度的常数。但是假设它们不超过O(N),则您的总体时间复杂度将为O(N^2)

相关问题