for (i = 0; i < 2*n; i += 2)
{
for (j=n; j > i; j--)
//some code that yields O(1)
}
I thought the above would yield n*log(n)
but I've seen another source say that it is really is n^2
complexity for big Oh. Please explain to me which it is and how i could approach problems like this in the future.
You have a loop that depends on n
and inside that loop you have another loop that also depends on n
, thus the resulting O is O(n*n)
ie O(n^2)
.
Big O only provides an upper bound on the growth rate of an algorithm. Thus all constant factors are discarded.
Since Big O is for Upper Bound, so N * N will always be <= N^2, resulting in O(N*2). Answer is right
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.