问题
func3(int n) {
for (int i = 1; i<n; i++)
System.out.println("*");
if (n <= 1)
{
System.out.println("*");
return;
}
if(n % 2 != 0) //check if odd
func3(n - 1)
func3(n / 2);
return;
}
I need to calculate the complexity of this algorithm, how can i do it when i have for in my code and 2 calls to func3?
回答1:
The bit pattern of n is very helpful in illustrating this problem.
Integer division of n by 2 is equivalent to right-shifting the bit pattern by one place, discarding the least significant big (LSB). e.g.:
binary
----------------------
n = 15 | 0000 1111
n / 2 = 7 (round down) | 0000 0111 (1) <- discard
- An odd number's LSB is always 1.
- An power-of-two only has 1 bit set.
Therefore:
The best case is when
nis a power-of-2, i.e.func3(n - 1)is only called once at the end whenn = 1. In this case the time complexity is:T(n) = T(n/2) + O(n) = O(n)What is the worst case, when
func3(n - 1)is always called once in each call tofunc3? The result ofn / 2must always be odd, hence:All significant bits of
nmust be 1.This corresponds to
nequal to a power-of-two minus one, e.g.3, 7, 15, 31, 63, ...In this case, the call to
func3(n - 1)will not yield another call to the same function, since ifnis odd thenn - 1must be even. Also,n / 2 = (n - 1) / 2(for integer division). Therefore the recurrence relation is:T(n) = 2 * T(n/2) + O(n) = O(n log n)
One can obtain these results via the Master theorem.
来源:https://stackoverflow.com/questions/49392291/calculate-complexity-of-recursion-algorithm