Bubble Sort Algorithm

Written by Tully on June 30, 2010 Categories: C++ Tags: , , ,

Was reading about sorting arrays in C++ and came across the bubble sort. Wikipedias definition says the bubble sort is a simple sorting algorithm. It works by repeatedly stepping through the list to be sorted, comparing each pair of adjacent items and swapping them if they are in the wrong order. The pass through the list is repeated until no swaps are needed, which indicates that the list is sorted. The algorithm gets its name from the way smaller elements “bubble” to the top of the list. Because it only uses comparisons to operate on elements, it is a comparison sort.

Example Bubble Sort Algorithm in C++

// Bubble Sort in C++
#include <iostream>
#include <iomanip>
using namespace std;

int main()
{

int num[ 10 ] = { 0, 2 ,1 ,55 ,22, 77, 32, 22, 77, 99 };
int numSize = 10;
int temp;

// Before sorting
cout << "Before the sort! " << endl;
for ( int i = 0; i < numSize; i++ )
cout << setw(5) << num[i];
cout << "nn";

for( int i = 0; i < numSize; i++ )
{
for (int j = 0; j < numSize; j++)
{
if ( num[i] < num[j] )
{
temp = num[i];
num[i] = num[j];
num[j] = temp;
}
}
}

cout << "After the sort!" << endl;
for ( int i = 0; i < numSize; i++ )
cout << setw(5) << num[i];
return 0;
}
No Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>