user11589840
user11589840

Reputation:

Worst-case time complexity of a recursive dividing function?

Given this algorithm:

void turtle_down(double val){
    if (val >= 1.0)
        turtle_down(val/2.0);
}

From what I know, T(n) = T(n/2) + O(1).

O(1) is the worst-case time complexity of the base function which is val != 0.0 (am i getting this right?). And then the recursive call gives a time complexity of T(n/2) since we divide n before the recursive call. Is that right?

But I don't understand how to do the math here. I don't know how will we arrive at O(log n)(base 2). Anyone care to explain or show me the math?

Upvotes: 0

Views: 397

Answers (1)

Deepu
Deepu

Reputation: 7610

void turtle_down(double val){
    if (val != 0.0)
        turtle_down(val/2.0);
}

In the above code, the test condition if (val != 0.0) may not give you the expected result. It would go into an infinite loop. Consider the case when val=32. You can see that it will never reach 0 by repeated division with 2.

But if you replace the test condition with say if (val >= 1) then recurrence relation for the given function will be T(n) = T(n/2) + O(1).

In this case the time complexity is T(n) = O(log n).

To get this result you can use the Master Theorem.

To understand the given complexity consider val = 32. You can divide val repeatedly by 2, for 5 times till it becomes 1. Notice that log 32 = 5. From this we can see that the number of calls made to the function is log n.

Upvotes: 0

Related Questions