Home » Programming » How to do a Bubble Sort

How to do a Bubble Sort

The purpose of a bubble sort is to accept any amount of numbers and sort each number from least to greatest or greatest to least.

So if we have 5 numbers 45, 1000, 46, 323, 67 we can sort them least to greatest like this:

45, 46, 67, 323, 1000

or

greatest to least

1000, 323, 67, 46, 45

Here is a clear example below

Ok, here is the beginning of the program, where we include headers

#include

All the elements of the standard C++ library are declared within what is called a namespace, the namespace with the name std. So in order to access its functionality we declare with this expression that we will be using these entities. This line is very frequent in C++ programs that use the standard library, and in fact it will be included in most of the source codes included in these tutorials.

using namespace std;

int main()
{

We then declare the variable we are going to experiment on

int hold;

Numbers in array to be sorted

int array[5]={ 10, 25, 35, 44, 11};

When performing a bubble sort we need two loops in this case I will use two for loops

for (int i=0; i<5; i++) {
for (int j=0; j<5; j++) {

This is the key part of the bubble sort, we use an if statement to execute a condition to sort the array from least to greatest. The way it works is by switching the previous variable in the array with the next variable in the array if the previous is greater than the next variable and use the variable hold as a container for the switching. If wanted to make it greatest to least we would merely switch around the greater than sign “>” to “<”.

if (array[j] > array[j+1]) {
hold = array[j+1];
array[j+1] = array[j];
array[j] = hold;
} // end of if

} // end of for
} // end of for

To print out the new sorted array

for (int x=0; x<5; x++) { cout << array[x] << ‘ ‘; }
cout << endl;

The return statement causes the main function to finish. return may be followed by a return code (in our example is followed by the return code 0). A return code of 0 for the main function is generally interpreted as the program worked as expected without any errors during its execution. This is the most usual way to end a C++ console program.

return 0;

} // end of main

Bookmark and Share

Popularity: 6% [?]

Random Posts

Leave a Reply

Copyright © 2010 · Comp Sci Solutions · All Rights Reserved · Posts · Comments