C or C++ Program for Bubble Sort

This article describes bubble sort program in c/c++. Let us discuss about Bubble sort.

What is Bubble Sort?
Bubble sort is the simplest sorting algorithm. Starting from the beginning of the list it’s compared every adjacent pair and swap their position if they are not in the right order (The latter one is smaller than the former one). This process is repeated as many times as necessary until the array is sorted. It takes O(n) time.

Bubble Sort Algorithm
The basic code for bubble sort looks like this, for sorting an integer array:

for(int x=0; x<n; x++)
{
   for(int y=0; y<n-1; y++)
   {
         if(array[y]>array[y+1])

         { 
               int temp = array[y+1];

               array[y+1] = array[y];

               array[y] = temp; 
         } 
    } 
}

Program for Bubble Sort

#include<iostream.h>
#include<conio.h>
int main(){
clrscr();
int n,i,j;
float tem,x[20];

cout<<" \" This program will arrange some data in Ascending order (using bouble sort). \""<<endl<<endl;

xx:
cout<<"How many numbers ?. Give a integer number."<<endl;
cin>>n;

if(n>20){
cout<<"More than 20 is not allow .Please give a number less than 20."<<endl;
goto xx;
}

if(n<0) {
cout<<"Negative numver not allow, Please give a integer number."<<endl;
goto xx;
}
if(n==0) {
cout<<"0 is not valid,Please give more."<<endl;
goto xx;
}

cout<<"What are the elements ?. Give some data."<<endl;
for(i=1;i<=n;i++)
cin>>x[i];

cout<<endl<<endl;
cout<<"You have given the following numbers :"<<endl;
for(i=1;i<=n;i++)
cout<<x[i]<<"  ";

for(i=1;i<=n;i++)
for(j=1;j<=n;j++) {
if(x[i]<x[j]) {
tem=x[i];
x[i]=x[j];
x[j]=tem;
}
}

cout<<endl;
cout<<"In Ascending order they are : "<<endl;
for(i=1;i<=n;i++)
cout<<x[i]<<"  ";

getch();
}

Leave a Reply

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