Bubble sort

Bubble sort is one of the most inefficient sorting algorithms because of how simple it is. While asymptotically equivalent to the other $$O(n^2)$$ algorithms, it will require $$O(n^2)$$ swaps in the worst-case. However, it is probably the simplest to understand, which accounts for its lack in efficiency. At each step, if two adjacent elements of a list are not in order, they will be swapped. Thus, smaller elements will "bubble" to the front, (or bigger elements will be "bubbled" to the back, depending on implementation) and hence the name "bubble sort". This algorithm is almost never recommended, as insertion sort has the same asymptotic complexity, but only requires $$O(n)$$ swaps. Bubble sort is stable, as two equal elements will never be swapped.

Pseudocode
a is an array of size n

swapped = true while swapped swapped = false for j from 0 to N - 1 if a[j] > a[j + 1] swap( a[j], a[j + 1] ) swapped = true

Optimizations
A small improvement can be made if each pass you keep track of whether or not an element was swapped. If not, you can safely assume the list is sorted.

Pseudocode
func bubblesort2( var a as array ) for i from 2 to N       swaps = 0 for j from 0 to N - 2 if a[j] > a[j + 1] swap( a[j], a[j + 1] ) swaps = swaps + 1 if swaps = 0 break end func

A second optimization can be made if you realize that at the end of the i-th pass, the last i numbers are already in place. Consider the sequence {3, 9, 1, 7}. After the first pass, the 9 will end up in the final position; we need not consider it on subsequent passes.

Pseudocode
func bubblesort3( var a as array ) for i from 1 to N       swaps = 0 for j from 0 to N - i          if a[j] > a[j + 1] swap( a[j], a[j + 1] ) swaps = swaps + 1 if swaps = 0 break end func

One can still improve the above optimization a little bit. Let a[k] and a[k+1] be the last two numbers swapped in the i-th pass. Then surely the numbers a[k+1] to a[n] are already in their final positions. In the next pass we only need to consider the numbers a[1] to a[k], i.e., loop from 1 to k-1. The above optimization only lets us ignore the last number of each pass; this optimization can ignore potentially many numbers in each pass.

Pseudocode
func bubblesort4( var a as array ) bound = N-1 for i from 1 to N       newbound = 0 for j from 0 to bound if a[j] > a[j + 1] swap( a[j], a[j + 1] ) newbound = j - 1 bound = newbound end func

A further improvement can be doing successive passes in opposite directions. This ensures that if one small number is at the end or one large number is at the beginning it reaches its final position in one pass.

= Implementations =

This algorithm is iterative.