具有两个循环和两个递归调用的算法的时间复杂度

时间:2016-01-03 17:23:48

标签: algorithm recursion time-complexity

这是一个用两个递归调用对数组进行排序的算法。我试图大致但不确定地计算它的时间复杂度。我知道两个for循环将需要n + n次但是如何处理递归调用以及如何处理我能计算出来吗?  任何人都可以用简单的数学方法帮助计算。

MySort (a[1..n] , n) {

         If (n <= 2) {
            If (first element > second) && (n = 2) then do
               { Interchange a[1] & a[2]; }
         End if
         }
         Else
         { Assign value to min and max by very first element of array.
         for (i : = 1 to n) do 
            { If (a[i] > max) then
              max = a[i]; 
         Else if (a[i] < min) then
                  min = a[i]; //Get max and min element from the array. }
         End for
         Calculate MID value of the MAXIMUM & MINIMUM element found. 
         For i : = 1 to n do 
         {
            If(a[i] < mid) then { Increment Count1 by 1; and P[Count1]=a[i] }
            Else if (a[i] > mid) then { Increment Count2 by 1; and Q[Count2]=a[i] } 
    //Divide the major array to sub-arrays; 
    //Count1 and Count2 are counters to make check on the size of sub-arrays generated. 
             }
        End for
        MySort (P, Count1);
           MSort (Q, Count2); }
        End if}

1 个答案:

答案 0 :(得分:0)

有两个循环,后跟两个递归调用。理想情况下,每次调用都会使输入的大小减半,从而产生n / 2个值。这给出了递归关系:

T(n) = n + n + T(n/2) + T(n/2)
T(n) = 2n + 2T(n/2)

这匹配Master theorem页面上给出的表格的最后一行:

T(n) = O(nlogn)

如果输入输入未按每次调用均分,那么它需要n ^ 2次,因为每次调用的大小可能只减少1次:

T(n) = 2n + T(n-1) + T(1)
T(n) = nT(1) + 2n + 2(n-1) + 2(n-2) + ...
T(n) = O(n^2)