I was going through below link enter link description here and going through answers I wanted to calculate time complexity of below suggested code. I played with quite a few values and number of steps are hovering between 23 (even for small values) and say 50 for real big values. How should I go about calculating time complexity for below code - Any pointers?
float val, low, high, mid, oldmid, midsqr;
// Set initial bounds and print heading.
low = 0; high = mid = val; oldmid = -1;
// Keep going until accurate enough.
while (fabs(oldmid - mid) >= 0.00001)
{
oldmid = mid;
// Get midpoint and see if we need lower or higher.
mid = (high + low) / 2;
midsqr = mid * mid;
if (mid * mid > val)
{
high = mid;
printf("- too high\n");
}
else
{
low = mid;
printf("- too low\n");
}
}
In terms of determining time complexity, think of how many "steps" your algorithm will take to terminate.
In this case, we are essentially binary searching to find the square root. Thus the number of steps we need to consider, is how many comparisons your algorithm makes. Because it is binary search, we know it is in the realm of O(log(n)), as you can think of binary search as halving the searchable space each time.
So now we need to figure out what n is. We are searching over the range (low, high), which is from (0, val). But because we are searching over floats, and the precision you care about is up to 0.00001, we can effectively multiply the range by 100000, to allow us to think of the problem on ints.
Then we will have a time complexity of O(log(100000 * val)) which is in O(log(val)) (unless precision is not constant).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With