Saturday, 21 September 2013

Program for Bubble Sort in C++ | Programming

Bubble sort is one of the simplest sorting algorithms . This algorithm has a quadratic order of growth and is therefore suitable for sorting small lists only . The algorithm works by repeatedly scanning through list , comparing adjacent elements , and swapping them if they are in the wrong order . The Algorithm gets its name from the way smaller elements "bubble" to top of the list after being swapped with greater elements . In this Tutorial I will be Discussing about the program for Bubble sort in C and C++ .


C++ Program for Bubble sort :


/*
File name : bubble.cpp
Code Written by : Lalith
Date : 21/08/2013
*/
#include<iostream>
using namespace std;
class bubble
{
 public :
  //Array of integers to hold values
  int arr[20];
 
  //Number of elements in array 
  int n;

  //Function to accept array elements
  void read()
  {
   while(1)
   {
    cout<<"\nEnter the number of elements in the array:";
    cin>>n;
    if(n<=20)
     break;
    else
     cout<<"\n Array can have maximum 20 elements \n";
   }
   //display the header
   cout<<"\n";
   cout<<"----------------------\n";
   cout<<"Enter array elements \n";
   cout<<"----------------------\n";
   
   //Get array elements
   for( int i=0; i<n ;i++ )
   {
    cout<<"<"<<i+1<<"> ";
    cin>>arr[i];
   }
  }
  //Bubble sort function
  void bubblesort()
  {
   for( int i=1;i<n ;i++ )//for n-1 passes
   {
    //In pass i,compare the first n-i elements
    //with their next elements 
    for( int j=0; j<n-1; j++)
    {
     if(arr[j] > arr[j+1])
     {
      int temp;
      temp = arr[j];
      arr[j] = arr[j+1];
      arr[j+1] = temp;
     }
    }
   }
  }
  void display()
  {
   cout<<endl;
   cout<<"----------------------\n";
   cout<<"Sorted array elements \n";
   cout<<"----------------------\n";
   for( int j=0; j<n; j++)
    cout<<arr[j]<<endl;
  }
 };
int main()
{
 //Instantiate an instance of class
 bubble list;
 // Function call to accept array elements
 list.read();
 // Function call to sort array
 list.bubblesort();
 //Function call to display the sorted array
 list.display();
 return 0;
} 

The above bubble sort code works perfectly with Linux G++ and Windows 32 and 64 bit compilers . 
Download the Bubble sort code from here .  

After compilation of bubble sort code the Output appears as shown below .

Feedback :

In my next tutorial of programming I will be discussing about Bubble sort algorithm and its timing complexity . If I had missed anything please get it to me through comments . Also share your programming experience and ideas through comments . 


1 comments:

  1. In the inner loop( j loop) no.of comparisons can be decreased as the outer loop variable i increases

    ReplyDelete