Juha said:
No, it isn't. It's O(n^2) regardless of how the input is arranged.
Even if you had a completely sorted input, it would still perform O(n^2)
steps. (Even if you put a check that would stop the sorting if no swaps
are done, even one single out-of-place element would still make it
perform O(n^2) steps.)
With that check, bubble sort performs n*m steps, where m is the maximum
distance an element has to be moved.
If the maximal distance is a constant, because your elements are
presorted and they only have to be moved, like, 5 steps, bubble sort
**in this case** is O(n).
But this is a very specific situation and I agree that insertion sort is
better.
I once had such a case:
<anecdote>
I programmed a traffic jam simulator, where the cars were object with a
x-axis floating point variable, which represented the position on the
street.
The cars were (bubble) sorted in each step by x, so that I could easily
check which car was in front of another car to simulate it's behaviour.
A car could pass another car, so that the sorting would swap them. The
street was an endless band, and a car which leaves on the right side
enters the street on the left side again (simply reset x to zero).
Each time a car left on the right side, the application stopped for a
second or two, because bubble sort was back to O(n^2) and moved the
object from the right side to the left.
As I didn't know about std::list and its sort function, and I didn't
know about sorting algorithms except bubble sort either (I was still in
school at the time), I manually removed the object from the linked list
and inserted it at the front.
</anecdote>
Short answer: Don't use bubble sort. Use the right algorithm for the job.