【问题标题】:Time complexity of an algorithm with two loops and two recursive calls具有两个循环和两个递归调用的算法的时间复杂度
【发布时间】:2016-04-07 08:53:10
【问题描述】:

这是一个用两个递归调用对数组进行排序的算法。我试图粗略地计算它的时间复杂度,但不确定。我知道两个 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}

【问题讨论】:

  • 请格式正确,带有缩进,每行一个语句。它是不可读的。
  • 我看不到 min、max、count1、count2 的初始化位置以及 mid 是如何计算的,所以这很可能会崩溃。
  • 顺便说一句。我看不到两个嵌套循环;并且两个嵌套循环不一定意味着 O (n^2) - 它取决于循环。
  • 它不是 c++ 代码,它的伪代码。通过数组的第一个元素为 min 和 max 赋值。解释了 min、max、count1、count2 的使用位置
  • 循环没有嵌套。

标签: algorithm recursion time-complexity


【解决方案1】:

有两个循环,后面跟着两个递归调用。理想情况下,每次调用都会将输入的大小减半,从而产生 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)

【讨论】:

  • 非常感谢@fgb 的帮助,每次递归调用时,输入都通过两个循环。一个循环划分数组,第二个循环只维护指向划分数组的最后一个元素的指针。可以你请详细解释这个答案。我猜你在这里使用了替换方法。 “T(n) = 2n + T(n-1) + T(1) T(n) = nT(1) + 2n + 2(n-1) + 2(n-2) + ... T( n) = O(n^2)"
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-10-07
  • 1970-01-01
  • 2020-10-05
  • 1970-01-01
  • 2011-08-17
相关资源
最近更新 更多