Wednesday, April 22, 2009

2 - Sorting Algorithm : Bubble Sort

One of the algorithm for sorting is Bubble Sort. It is called bubble sort because the way it sorts is like bubble in a glass of soda. The smallest integer will "bubble up" after the sorting. The program bellow is an example of such algorithm. It ascending sorts the array.

#include "iostream"
using namespace std;

int main (void)
{
int arrInt[8] = {5, 6, 3, 4, 8, 9, 2, 1};
int i;
int j;
int temp;

cout << endl;
for (i = 0; i < 8; i++)
{
cout << arrInt[i];
}

for (j=0; j<8;j++)
{
for (i = 0; i < 7; i++)
{
if (arrInt[i] > arrInt[i+1])
{
temp = arrInt[i];
arrInt[i] = arrInt[i+1];
arrInt[i+1] = temp;
}
}
}

cout << endl;
for (i = 0; i < 8; i++)
{
cout << arrInt[i];
}
}


Next we have another example descending sort :

#include "iostream"
using namespace std;

int main (void)
{
int arrInt[8] = {5, 6, 3, 4, 8, 9, 2, 1};
int i;
int j;
int temp;

cout << endl;
for (i = 0; i < 8; i++)
{
cout << arrInt[i];
}

for (j=0; j<8;j++)
{
for (i = 0; i < 7; i++)
{
if (arrInt[i] < arrInt[i+1])
{
temp = arrInt[i];
arrInt[i] = arrInt[i+1];
arrInt[i+1] = temp;
}
}
}

cout << endl;
for (i = 0; i < 8; i++)
{
cout << arrInt[i];
}
}

The bubble sort algorithm is arguably one of the easiest algorithm to memorize even though it is not particularly efficient. Therefore next we are going to explore another sorting algorithm : Selection Sort for sorting an array in ascending and descending manners.