Bubble sort and selection sort both have average and worst-case time complexity of and auxiliary space complexity of . However, an optimized bubble sort has a best-case time complexity of , while selection sort remains even when the data is already sorted.
Here, represents the number of elements in the array.
| Algorithm | Best time | Average time | Worst time | Auxiliary space |
|---|---|---|---|---|
| Optimized bubble sort |
Bubble sort repeatedly compares adjacent elements and swaps them if they are in the wrong order. Across its passes, the number of comparisons is approximately
which grows proportionally to . An optimized version uses a Boolean flag to stop after one pass with no swaps, producing time for already sorted data.
Selection sort repeatedly searches the unsorted section for its minimum element and places it in the next sorted position. It still performs approximately comparisons regardless of the original order, so its best, average, and worst cases are all .
Although their asymptotic time is the same, their operation counts differ. Selection sort performs at most swaps, whereas bubble sort can perform swaps in reverse order. This matters when writes are expensive, but it does not change either algorithm's classification. Big O ignores constant factors and lower-order terms in growth.
Both are in-place algorithms because they use only a fixed number of extra variables. Therefore, their auxiliary space does not increase with , giving .
A common misconception is that selection sort becomes faster in Big O terms when the array is sorted. It may perform fewer swaps than bubble sort, but it still checks every remaining element when selecting each minimum.
For IB Computer Science B2.4, state the case being analysed, define , and justify the complexity using passes or comparisons. Do not give only the Big O value when the command term is explain.