问题
Here is an algorithm of sorting an array with two recursive calls.I have tried to calculate its time complexity roughly but not sure.I know that two for loops will take n+n times but what to do with recursive calls and how can i calculate them? Any one can help in calculating in simple mathematical way.
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:
There are two loops followed by two recursive calls. Ideally, each call would halve the size of the input, resulting in n/2 values. This gives a recurrence relation:
T(n) = n + n + T(n/2) + T(n/2)
T(n) = 2n + 2T(n/2)
This matches the last row of the table given on the Master theorem page:
T(n) = O(nlogn)
If the input input is not evenly divided each call, then it instead takes n^2 time, as the size could possibly only be reduced by 1 each call:
T(n) = 2n + T(n-1) + T(1)
T(n) = nT(1) + 2n + 2(n-1) + 2(n-2) + ...
T(n) = O(n^2)
来源:https://stackoverflow.com/questions/34579369/time-complexity-of-an-algorithm-with-two-loops-and-two-recursive-calls