Bubble sort is the one of the oldest algorithm to sort an array. Bubble sort works by comparing each value with the element below it and if the upper value is greater then the lower one then these values are swapped(if we have to sort the array in ascending order), so by this process the highest value will be at the last element of the array. If this process is repeated n(size of array) times then the whole array would be sorted.

Wikipedia has a very good page explaining Bubble Sort but the code examples are not that easy. I have written this C++ code to bubble sort an array in a very simple and understandable way using Microsoft Visual C++ 2008:

#include "stdio.h"
#include "conio.h"
#include "iostream"//if using Turbo C use iostream.h
using namespace std;

void main()
{
int myarray[10];//declearing an array
int i,j; //declearing valriable which will be used in looping
int hold; //this variable will be used for the interchanging of the variable

for(i = 0;i<10;i++)
{
//taking inputs for the array
printf("nEnter the value of the array at position %d : ",i+1);
scanf("%d",&myarray[i]);
}

//loop will run as the size of the array
for(i=0;i<10;i++)
{
//The loop will run till highest weighed element is set at its position
for(j = 0;j<(9-i);j++)
    {
    if(myarray[j] > myarray[j+1])//interchanging the values
             {
                hold= myarray[j];
                myarray[j] = myarray[j+1];
                myarray[j+1] = hold;
                }
    }
}

for(i = 0;i<10;i++)
{
    //taking inputs for the array
printf("nThe value of the array at position %d is %d",i+1,myarray[i]);
}
}

Download the Visual Studio 2008 C++ solution file: bubble.zip

Like this article? Subscribe to our feeds for more interesting and original technology updates. Click here to get updates via email. You can also join our Facebook fan page