Pages

Monday 8 November 2021

Program to illustrate Bubble sort in c++

 Program to illustrate Bubble sort Program in oops

#include<iostream.h>
#include<conio.h>
class Bubblesort
{
public:
  int a[10],i,j,temp,n;
public:
  void getdata();
  void sort();
  void display();
};
void Bubblesort::getdata()
{
cout<<"Enter the size"<<endl;
cin>>n;
cout<<"Enter the elements"<<endl;
for(i=0;i<n;i++)
cin>>a[i];
}
void Bubblesort::sort()
{
for(i=0;i<n;i++)
{
  for(j=0;j<n-i;j++)
  {
    if(a[j]>a[j+1])
     {
      temp=a[j];
      a[j]=a[j+1];
      a[j+1]=temp;
     }
   }
 }
 }
 void Bubblesort::display()
 {
   cout<<"Elements after sorting"<<endl;
   for(i=0;i<n;i++)
   cout<<"   "<<a[i];
 }
 void main()
 {
   Bubblesort b;
   clrscr();
   b.getdata();
   b.sort();
   b.display();
   getch();
 }


//Bubblesort with Address -- Array -- Data -- Location
#include<iostream.h>
#include<conio.h>
class Bubblesort
{
public:
  int a[10],i,j,temp,n;
public:
  void getdata();
  void sort();
  void display();
};
void Bubblesort::getdata()
{
cout<<"Enter the size"<<endl;
cin>>n;
cout<<"Enter the elements"<<endl;
for(i=0;i<n;i++)
cin>>a[i];
cout<< "Elements before sorting:";
for(i=0;i<n;i++)
 {
 cout<<"\n\tAddress :"<<&a[i]<<"\tArray :"<<"a["<<i<<"]"<<"\tData :"<<a[i]<<"\tLocation :"<<i+1;
 cout<<"\n";
 }
}
void Bubblesort::sort()
{
for(i=0;i<n;i++)
{
  for(j=0;j<n-i;j++)
  {
    if(a[j]>a[j+1])
     {
      temp=a[j];
      a[j]=a[j+1];
      a[j+1]=temp;
     }
   }
 }
}
 void Bubblesort::display()
 {
 cout<< "Elements after sorting:";
 for(i=0;i<n;i++)
 {
  cout<<"\n\tAddress :"<<&a[i]<<"\tArray :"<<"a["<<i<<"]"<<"\tData :"<<a[i]<<"\t Location :"<<i+1;
  cout<<"\n";
 }
}

void main()
 {
   Bubblesort b;
   clrscr();
   b.getdata();
   b.sort();
   b.display();
   getch();
 }
Output:

Bubble sort animation video link:
https://www.youtube.com/watch?v=Bi8xZLuydWY

No comments:

Post a Comment

Constructors & Destructors in c++

  Constructors :  A Constructor is a special member function, which is used to initialize the objects of its class. The Constructor is invok...