Implementation of Bubble Sort Using Templates
Implementation of Bubble Sort Using Templates
#include<iostream.h> #include<conio.h> template<class T> void bubble(T a[],int n) { for(int i=0;i<n-1;i++) { for(int j=n-1;i<j;j--) { if(a[j]<a[j-1]) { swap(a[j],a[j-1]); } } } } template<class X> void swap(X &a,X &b) { X temp=a; a=b; b=temp; } int main() { int X[100],n,i,j; float Y[100]; clrscr();
cout<<"\nEnter no of elements:"; cin>>n; cout<<"\nEnter the "<<n<<" integer values to be sorted:"; for(i=0;i<n;i++) { cin>>X[i]; } cout<<"\nEnter the "<<n<<" floating-point values to be sorted:"; for(i=0;i<n;i++) { cin>>Y[i]; } bubble(X,n); bubble(Y,n); cout<<"\nThe sorted integer array elements are:\n"; for(i=0;i<n;i++) cout<<X[i]<<"\t"; cout<<endl; cout<<"\nThe sorted floating point array elements are:\n"; for(i=0;i<n;i++) cout<<Y[i]<<"\t"; getch(); return 0; }
{ cin>>X[i]; } cout<<"\nEnter the "<<n<<" floating-point values to be sorted\n"; for(i=0;i<n;i++) { cin>>Y[i]; } insertion(X,n); insertion(Y,n); cout<<"\nThe sorted integer array elements are:"; for(i=0;i<n;i++) cout<<X[i]<<"\t"; cout<<endl; cout<<"\nThe sorted floating point array elements are:"; for(i=0;i<n;i++) cout<<Y[i]<<"\t"; getch(); return 0; }
#include<iostream.h> #include<conio.h> template<class w> class quick { w a[50]; int n; public: void get(); void sort(int,int); int partition(int,int); void put(); }; template<class w> void quick<w>::get() { int i; cout<<"\n enter the no of terms:"; cin>>n; cout<<"enter the values:"; for(i=1;i<=n;i++) cin>>a[i]; sort(1,n); } template<class w> void quick<w>::sort(int p,int q) { int j;
if(p<q) { j=partition(p,q+1); sort(p,j-1); sort(j+1,q); } } template<class w> int quick<w>::partition(int m,int p) { int i,j,t; w v; v=a[m]; i=m;j=p; do { do i++; while(a[i]<v); do j--; while(a[j]>v); if(i<j) { t=a[i]; a[i]=a[j]; a[j]=t; } } while(i<j); a[m]=a[j];
a[j]=v; return j; } template<class w> void quick<w>::put() { int i; for(i=1;i<=n;i++) cout<<a[i]<<" "; } void main() { clrscr(); quick<int> q1; quick<float> q2; cout<<"\nquick sort using template"; q1.get(); cout<<"\nsorted array of integer values:"; q1.put(); q2.get(); cout<<"\n\nsorted array of floating values:"; q2.put(); getch(); }
{ if(n>1) { int n1=n/2; int n2=n-n1; sort(a,n1); sort(a+n1,n2); merge(a,n1,n2); } } void main() { int a[]={12,11,15,13,17,14,16,19,18}; cout<<"\n Before sorting"; print(a,9); sort(a,9); cout<<"\n After sorting\n"; print(a,9); char ch[]={'b','d','a','f','g','j','r','u','s'}; cout<<"\n Before sorting\n"; print(ch,9); sort(ch,9); cout<<"\n After sorting\n"; print(ch,9); }