Bubble Sort Analysis
Bubble Sort Analysis
One of the simplest sorting algorithm.
The basic idea is to move required value (smallest or highest ) to the top in array.
- Compare adjacent values (all elements)
- Swap values if required
- Repeat the comparisons until all the elements are in place
C++ Code for bubble sort using loop
#include <iostream.h>
int main()
{
const int arraySize=10;
int a[ 10] = { 2, 6, 4, 8, 10, 12, 89, 68,45,37 };
int hold; // temporary location used to swap arrayelements
cout << “Data items in original order\n”; // output original array
for ( int i = 0; i < arraySize; i++ )
cout << a[ i ];
for ( int pass = 0; pass < arraySize – 1; pass++ ) // loop to control number of passes
for ( int j = 0; j < arraySize – 1; j++ ) // loop to control number of comparisons per pass
if ( a[ j ] > a[ j + 1 ] ) // compare side-by-side elements and swap them if first element is greater than second element
{
hold = a[ j ];
a[ j ] = a[ j + 1 ];
a[ j + 1 ] = hold;
} // end if
cout << “\nData items in ascending order\n”;
for ( int k = 0; k < arraySize; k++ ) // output sorted array
cout << a[ k ];
cout << endl;
return 0; // indicates successful termination
} // end main
Analysis of Bubble sort
for i= 1 to n-1
for j= 1 to n-1n
if A[j] > a[j+1] then
swap(A[j],A[j+1])
(N-1) steps executed (N-1) times
- (n-1)*(n-1) = O(n2)