#include <iostream>
#include <cstdlib>
#include <ctime>
#include <string>//swap function predefined. Not Used ( optional )
usingnamespace std;
void printArray( int[ ], int );
void swap( int&, int& ); //user defined swap
int main()
{
constint SIZE = 20;
int myArray[ SIZE ] = {0};
srand((unsignedint )time(NULL));
for ( int i = 0; i < SIZE; i++ )
myArray[ i ] = rand() % 100;
///start the insertion sort algorithm
for ( int iIndex = 1; iIndex < SIZE; iIndex++ ) //Insertion Sort Algorithm
{
int TEMP = myArray[ iIndex ]; //the key
int ELEMENT = iIndex; // insert position
while ( ELEMENT > 0 && myArray[ ELEMENT - 1 ] > TEMP )
{
swap( myArray[ ELEMENT ], myArray[ ELEMENT - 1 ]);
ELEMENT--;
}
}
cout << "Insertion Sorting: \t";
printArray(myArray,SIZE);
//Start the Bubble Sort algorithm
for ( int iIndex = SIZE - 1; iIndex > 0; iIndex-- ) // Bubble Sort Algorithm
{
for ( int i = 0; i < iIndex; i++ )
if ( myArray[i] > myArray[i+1] )
swap( myArray[i],myArray[i+1] );
}
cout << "Bubble Sorting: \t";
printArray(myArray,SIZE);
return 0;
}
void printArray( int a[], int SIZE )
{
for ( int j = 0; j < SIZE; j++ )
cout << a[ j ] << ' ';
cout << endl;
}
void swap( int &T1, int &T2 )
{
int temp = T1;
T1 = T2;
T2 = temp;
}
What is the advantage(s) of bubble sort over Insertion sort?
Do programmers into more complex algorithm for sorting arrays still make use of the insertion sort,
and bubble sort since some say the algorithm is slow and of low performance.
What is the advantage(s) of bubble sort over Insertion sort?
I don't know of any.
Insertion sort have some good properties. It is online, and performs well in almost sorted arrays.
I read somewhere that for small input it may perform better than the optimal O(n lg n) algorithms, so you can use it in the base case of quick-sort.
¿You realize that you are passing a sorted array to your bubble sort?