## C++ Bubble Sort

Bubble sort is a simple and well-known sorting algorithm. It is used in practice once in a blue moon and its main application is to make an introduction to the sorting algorithms. Bubble sort belongs to O(n^{2}) sorting algorithms, which makes it quite inefficient for sorting large data volumes. Bubble sort is **stable** and **adaptive**.

## Algorithm

- Compare each pair of adjacent elements from the beginning of an array and, if they are in reversed order, swap them.
- If at least one swap has been done, repeat step 1.

You can imagine that on every step big bubbles float to the surface and stay there. At the step, when no bubble moves, sorting stops. Let us see an example of sorting an array to make the idea of bubble sort clearer.

## Complexity analysis

Average and worst case complexity of bubble sort is O(n^{2}). Also, it makes O(n^{2}) swaps in the worst case. Bubble sort is adaptive. It means that for almost sorted array it gives O(n) estimation. Avoid implementations, which don’t check if the array is already sorted on every step (any swaps made). This check is necessary, in order to preserve adaptive property.

One more problem of bubble sort is that its running time badly depends on the initial order of the elements. Big elements (rabbits) go up fast, while small ones (turtles) go down very slow. This problem is solved in the Cocktail sort.

## Code

#include<iostream> using namespace std; #include<iomanip> using std::setw; int main() { const int arraysize = 10; int Bubble[ arraysize ]; cout << "Please enter 10 integers: " << endl; for ( int i = 0; i < arraysize; i++ ) cin >> Bubble[ i ]; cout <<"unsorted array:\n"; for ( int j = 0; j < arraysize; j++ ) cout << setw( 4 ) << Bubble[ j ]; for(int y=0; y < arraysize; y++) { for ( int k =0; k < arraysize -1-y; k++ ) if(Bubble[k]>Bubble[k+1]) { int temp = Bubble[k+1]; Bubble[k+1] = Bubble[k]; Bubble[k] = temp; } } cout << "\nSorted Bubble array:\n"; for (int l = 0; l < arraysize; l++ ) cout << setw( 4 ) << Bubble[ l ]; cout << endl; return 0; }

this article was exactly what i have been searching for! found this article bookmarked from a friend. I will also share it. Thanks again!