Bubble Sort and Insertion Sort

closed account (SGb4jE8b)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60

#include <iostream>
#include <cstdlib>
#include <ctime>
#include <string>//swap function predefined. Not Used ( optional )
using namespace std;

void printArray( int[ ], int );
void swap( int&, int& ); //user defined swap

int main()
{
	const int SIZE = 20;
	int myArray[ SIZE ] = {0};

	srand((unsigned int )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.
Last edited on
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?
Last edited on
closed account (SGb4jE8b)
Yes! Thanks. But when I read about the Bubble Sort, they Say is superior to insertion Sort. I don't get it. I can't see the Superiority.
Topic archived. No new replies allowed.