Bubble sort

Program Description

Implementation of bubble sort using object orientation in C++.Sorts an array of integer elements in ascending order using the bubble sort algorithm.

Program
/*************************************
*  code.cheraus.com
*  
*  Bubble sort
*
**************************************/

#include<iostream>

using namespace std;

// Class definition
class bubble{

private:
        int list[50],n;  //integer array
public:

        //public functions to interact with the object
        void getdata();  
        void sort();
        void display();
};
/*
Function definition for getdata()

The function takes input from the user and stores them in the 
array. Expects only integer inputs.

*/
void bubble::getdata()
{
  cout<<"\nEnter the number of elements : ";
  cin>>n;
  
  
  for(int i=0;i<n;i++)
   {
     cout<<"\nEnter the "<<i+1<<" element : ";
     cin>>list[i];
   }
}


/*
Function definition for bubble()

This function displays the contents of the integer array of the called object.

*/

void bubble::display()
{
  cout<<"{\t";
  for(int i=0;i<n;i++)
   {
     cout<<list[i]<<"\t";
   }
  cout<<"}\n";
}


/*
Function definition for sort()

This function sorts the data elements in the integer array in ascending order using 
the bubble sort algorithm.

*/
void bubble::sort()
{
  int i=0,j=0,temp;
  for(i=0;i<n;i++)
   {
     for(j=0;j<n-i-1;j++)
      {
         if(list[j]>list[j+1])
         {
            
			//swapping of elements if first is greater than the second
			temp = list[j];
            list[j] = list[j+1];
            list[j+1] = temp;
         }
      }
   }
}


//start of main function
int main()
{
  bubble b;   //object declaration
  b.getdata();  //filling data in the object
  
  //displaying the data before sorting
  cout<<"\nElements before sorting : ";
  b.display();
  
  //sorting the data
  b.sort();
  
  //displaying the sorted data
  cout<<"\nElements after sorting : ";
  b.display();
  
  
  return 0;
}

Output
Test Case 1:

Enter the number of elements : 8
Enter the 1 element : 8
Enter the 2 element : 7
Enter the 3 element : 6
Enter the 4 element : 5
Enter the 5 element : 4
Enter the 6 element : 3
Enter the 7 element : 2
Enter the 8 element : 1
Elements before sorting : { 8 7 6 5 4 3 2 1 }
Elements after sorting : { 1 2 3 4 5 6 7 8 }

Test Case 2:

Enter the number of elements : 4
Enter the 1 element : 3
Enter the 2 element : 2
Enter the 3 element : 1
Enter the 4 element : 4
Elements before sorting : { 3 2 1 4 }
Elements after sorting : { 1 2 3 4 }

Comments
comments powered by Disqus