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
a is an array size n

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

C++
a is an array,n is the size of the array

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.

Pseudo-code

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

C++

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.

Pseudo-Code

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

C++

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.

Pseudo-Code

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

C++

Java
This code asks for the no. of elements in the array and then you can enter unsorted array. It prints sorted array using BubbleSort

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

 * C iterative