How is O(N) algorithm also an O(N^2) algorithm?

荒凉一梦 提交于 2020-12-08 06:15:20

问题


I was reading about Big-O Notation

So, any algorithm that is O(N) is also an O(N^2).

It seems confusing to me, I know that Big-O gives upper bound only.

But how can an O(N) algorithm also be an O(N^2) algorithm.

Is there any examples where it is the case?

I can't think of any.

Can anyone explain it to me?


回答1:


"Upper bound" means the algorithm takes no longer than (i.e. <=) that long (as the input size tends to infinity, with relevant constant factors considered).

It does not mean it will ever actually take that long.

Something that's O(n) is also O(n log n), O(n2), O(n3), O(2n) and also anything else that's asymptotically bigger than n.

If you're comfortable with the relevant mathematics, you can also see this from the formal definition.




回答2:


O notation can be naively read as "less than".

In numbers if I tell you x < 4 well then obviously x<5 and x< 6 and so on.

O(n) means that, if the input size of an algorithm is n (n could be the number of elements, or the size of an element or anything else that mathematically describes the size of the input) then the algorithm runs "about n iterations".

More formally it means that the number of steps x in the algorithm satisfies that:

x < k*n + C where K and C are real positive numbers

In other words, for all possible inputs, if the size of the input is n, then the algorithm executes no more than k*n + C steps.

O(n^2) is similar except the bound is kn^2 + C. Since n is a natural number n^2 >= n so the definition still holds. It is true that, because x < kn + C then x < k*n^2 + C.

So an O(n) algorithm is an O(n^2) algorithm, and an O(N^3 algorithm) and an O(n^n) algorithm and so on.




回答3:


Definition of big-O:

Some function f(x) is O(g(x)) iff |f(x)| <= M|g(x)| for all x >= x0.

Clearly if g1(x) <= g2(x) then |f(x)| <= M|g1(x)| <= M|g2(x)|.




回答4:


For something to be O(N), it means that for large N, it is less than the function f(N)=k*N for some fixed k. But it's also less than k*N^2. So O(N) implies O(N^2), or more generally, O(N^m) for all m>1.

*I assumed that N>=1, which is indeed the case for large N.




回答5:


Big-O notation describes the upper bound, but it is not wrong to say that O(n) is also O(n^2). O(n) alghoritms are subset of O(n^2) alghoritms. It's the same that squares are subsets of all rectangles, but not every rectangle is a square. So technically it is correct to say that O(n) alghoritm is O(n^2) alghoritm but it isn't precise.



来源:https://stackoverflow.com/questions/44341669/how-is-on-algorithm-also-an-on2-algorithm

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!