Bubble sort

Bubble sort is one of the most inefficient sorting algorithms. 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. 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. 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.

Pseudo-code
func bubblesort( var a as array ) for i from 1 to N       for j from 1 to N - 1 if a[j] > a[j+1] swap( a[j], a[j+1] ) end func

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.

func bubblesort2( var a as array ) for i from 1 to N       swaps = 0 for j from 1 to N - 1 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 nth pass, the last n 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.

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

Real bubble sort (good optimization)
Down here is the (almost) original bubble sort but it has a SANTINEL (variable j) to make the algorithm a little fster. to make it even faster you after u use for i from j2 -> n-j .. to use the same way again a for i from n-j -> j2 this way you implement another santinel which makes it faster. ;) func bubblesort( var a as array )    j=1     repeat           q=0;             for i from 1 to N - j                     if a[i] > a[i+1] then{                            swap( a[i], a[i+1] )                            q=1; l=i;}            j=l;     while q; end func