问题
I have some code and the text is
For following code, find a lower and upper bound if data for function f,g is given, and we know that is best and worst case is given, condition is fulfilled in most cases.
f:O(log(n)), and lower bound is 1
g:O(n) and lower bound is (logn)^2
I think that first line of my code is logn, then since n>log(n) I think that second line is O(n*log(n))and the last lines is nlogn I think because if I use summarization I get logn(n+(logn)^2-1) end then the O is O(n^2(logn)^2). And for lower bound is n(logn)^3 i am beginner in this so please tell me where I make a mistake. Thank you
for(int i=n;i>0;i/=2)
if(f()<=g())
for(int j=f()*f();j<n;j++)
f()
回答1:
Your code is badly formatted so it is not really clear what the code flow is. Assuming your code is actually equivalent to:
for(int i=n; i>0; i/=2) {
if(f()<=g()) {
for(int j=f()*f(); j<n; j++) {
f();
}
}
}
You need to find the best and the worst case performance.
IMHO it is easier to go from inside to the outside (at least until you get more experience):
The inner-most call
f()
isO(log(n))
in the worst case andO(1)
in the best case.Since
f()*f()
is a constant the inner loop isO(n)
times the previous step (which isf()
) + 2 timesf()
for the initial value ofj
+ there are alsoO(n)
condition checks andO(n)
increments which together can be expressed as a singleO(n)
. So for the worst case it isO(n*log(n) + 2*log(n) + n)
which isO(n*log(n))
and for the best case it isO(n*1 + 2 + n)
which isO(n)
The
if
itself is just time of the calculation off()
andg()
. Since the condition is mostly true, we just add the cost of the inner loop. So for the worst case it isO(log(n) + n + n*log(n))
which isO(n*log(n))
and for the best case it isO(1 + log^2(n) + n)
which isO(n)
(O(n)
dominatesO(log^2(n))
)The outer loop as you correctly noticed is always
O(log(n))
times. So the total complexity isO(log(n))
times of the body (+ not forget about the check and increment, this might make a difference if the condition is mostly false). So the worst case isO(log(n)*n*log(n)+log(n))
which isO(n*log^2(n))
and the best case isO(log(n)*n + log(n))
which isO(n*log(n))
.
Hopefully I didn't mess up with details. But the most important thing is to understand when to add an when to multiply; and to understand which part dominates the others when you simplify.
来源:https://stackoverflow.com/questions/54162589/how-to-find-a-upper-and-lower-bound-of-code