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

Viewed 23124

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?

6 Answers

For an algorithm with just a single Loop will get a O(n) and algorithm with a nested loop will get a O(n^2). Now consider the Bubble sort algorithm it uses the nested loop in it,

If we give an already sort set of inputs to a bubble sort algorithm the inner loop will never get executed so for a scenario like this it gets O(n) and for the other cases it gets O(n^2).

Related