Program of Bubble Sort Using C++
Program of Bubble Sort Using C++
CPP
#include<iostream.h> #include<conio.h> #include<string.h> class bublsort { int n,a[50],t,k,counter,swapped; public : bublsort(); void getdata(); void dosorting(); }; bublsort::bublsort() { k=0; counter=0; swapped=0; }
Page 1
void bublsort::getdata() { cout<<"Enter the number of elements to sort:"; cin>>n; cout<<"\nEnter the elements to sort:\n"; for ( int i=0;i<n;i++) { counter++; cin>>a[i]; } } void bublsort::dosorting() { if (counter>n) { cout<<"Entered number exceed the "<<n; } else { for ( int i=1;i<n;i++) { for ( int j=0;j<n-i;j++) { if (a[j]>a[j+1]) { t=a[j]; a[j]=a[j+1]; a[j+1]=t; swapped=1; } } if (!swapped) { break ; //swapped flag is used to check if the array is already sorted. } cout<<"\n\nOutput of Pass "<<i<<" of bubble sort is :\n"; for (k=0;k<n;k++) cout<<" "<<a[k]<<" "; } cout<<"\n\nSorted array by bubble sort:\n"; for (k=0;k<n;k++) cout<<" "<<a[k]<<" "; } } int main() { cout<<"\n----------BUBBLE SORT----------\n\n"; bublsort obj;
BUBWCL.CPP
obj.getdata(); obj.dosorting();
Page 2
cout<<"\n\n-------------END-------------"; return 0; }