【发布时间】: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