Search Here

C++ program to implement Generic Bubble Sort

/* C++ program for Generic Bubble Sort */

#include<iostream>
#include<stdlib.h>
using namespace std;

template<class type>
class sorting
{
    int s,n; //by default private
    type *p;//by default private
    public: sorting(int);
            void getdata();
            void showdata();
            void bubble();
            ~sorting();
};

template<class type>
sorting<type> :: sorting(int s1)
{
    s=s1;
    if(s>0)
        p=new type[s];
    else
    {
        cout<<"\n Size of the array is zero or negative";
        exit(0);
    }
}

template<class type>
void sorting<type> :: getdata()
{
    cout<<"\n Enter the number of elements:";
    cin>>n;
    if(n>0&&n<=s)
    {
        cout<<"\n Enter the elements in the array to sort:";
        for(int i=0;i<n;i++)
            cin>>p[i];
    }
    else
    {
        cout<<"\n Number of elements can not be zero or negative or greater than size of the array";
        exit(0);
    }
}

template<class type>
void  sorting<type> :: showdata()
{
    for(int i=0;i<n;i++)
        cout<<"\t"<<p[i];
}

template<class type>
void  sorting<type> :: bubble()
{
    int t;
    int flag=1;
    for(int i=1;i<=n && flag;i++)
    {
        flag=0;
        for(int j=0;j<(n-1);j++)
        {
            if(p[j]>p[j+1])
            {
                t=p[j];
                p[j]=p[j+1];
                p[j+1]=t;
                flag=1;
            }
        }
    }
}

template<class type>
sorting<type> :: ~sorting()
{
    delete[] p;
    cout<<"\n Object destroyed";
}

int main()
{
    sorting<int> A(10); //Integer elements
    cout<<"\n\t***Integer elements***";
    A.getdata();
    cout<<"\nArray elements before sorting:";
    A.showdata();
    A.bubble();
    cout<<"\nArray elements after sorting:";
    A.showdata();
    sorting<char> B(10); //Character elements
    cout<<"\n\n\t***Character elements***";
    B.getdata();
    cout<<"\nArray elements before sorting:";
    B.showdata();
    B.bubble();
    cout<<"\nArray elements after sorting:";
    B.showdata();
    sorting<double> X(10); // Float elements
    cout<<"\n\n\t***Float elements***";
    X.getdata();
    cout<<"\nArray elements before sorting:";
    X.showdata();
    X.bubble();
    cout<<"\nArray elements after sorting:";
    X.showdata();
    
    return(0);
}


Generic Bubble Sort
Output

No comments:

Post a Comment