Bubble sort, sometimes incorrectly referred to assinking sort, is a simplesorting algorithmthat works by repeatedly stepping through the list to be sorted, comparing each pair of adjacent items andswappingthem if they are in the wrong order. The pass through the list is repeated until no swaps are needed, which indicates that the list is sorted. The algorithm gets its name from the way smaller elements "bubble" to the top of the list. Because it only uses comparisons to operate on elements, it is acomparison sort. Although the algorithm is simple, most of the other sorting algorithms are more efficient for large lists.

Performance

Bubble sort has worst-case and average complexity bothО(n2), wherenis the number of items being sorted. There exist many sorting algorithms with substantially better worst-case or average complexity ofO(n log n). Even otherО(n2) sorting algorithms, such asinsertion sort, tend to have better performance than bubble sort. Therefore, bubble sort is not a practical sorting algorithm whennis large.

The only significant advantage that bubble sort has over most other implementations, evenquicksort, but notinsertion sort, is that the ability to detect that the list is sorted is efficiently built into the algorithm. Performance of bubble sort over an already-sorted list (best-case) isO(n). By contrast, most other algorithms, even those with betteraverage-case complexity, perform their entire sorting process on the set and thus are more complex. However, not only doesinsertion sorthave this mechanism too, but it also performs better on a list that is substantially sorted (having a small number ofinversions).