Algorithm 具有两个循环和两个递归调用的算法的时间复杂度
这是一个使用两个递归调用对数组进行排序的算法。我尝试粗略地计算它的时间复杂度,但不确定。我知道两个for循环需要n+n次,但如何处理递归调用,如何计算它们? 任何人都可以用简单的数学方法帮助计算Algorithm 具有两个循环和两个递归调用的算法的时间复杂度,algorithm,recursion,time-complexity,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
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}
MySort(a[1..n],n){
如果(n秒)和(n=2),则执行
{交换a[1]&a[2];}
如果结束
}
其他的
{通过数组的第一个元素为最小值和最大值赋值。
对于(i:=1到n)do
{如果(a[i]>max)那么
max=a[i];
否则,如果(a[i]mid),则{将Count2增加1;并且Q[Count2]=a[i]}
//将主数组划分为子数组;
//Count1和Count2是检查生成的子数组大小的计数器。
}
结束
MySort(P,Count1);
MSort(Q,Count2);}
结束如果}
有两个循环,后跟两个递归调用。理想情况下,每次调用都会将输入大小减半,从而得到n/2的值。这给出了一个递归关系:
T(n) = n + n + T(n/2) + T(n/2)
T(n) = 2n + 2T(n/2)
这与页面上给出的表格的最后一行相匹配:
如果输入不是平均分配给每个调用,则需要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)
请使用缩进格式,每行一条语句。它是不可读的。我看不到最小值,最大值,count1,count2在哪里初始化,以及mid是如何计算的,所以这很可能会崩溃。顺便说一句。我看不到两个嵌套的循环;两个嵌套循环并不一定意味着O(n ^ 2)-它取决于循环。它不是C++代码的伪代码。通过数组的第一个元素赋值给Min和Max。Min,Max,Cord1,CurnT2被解释为:它们使用的循环不是嵌套的。感谢ALOT@ 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)”
T(n) = 2n + T(n-1) + T(1)
T(n) = nT(1) + 2n + 2(n-1) + 2(n-2) + ...
T(n) = O(n^2)