Saturday 22 October 2011

Program on Bubble Sort


#include<iostream>
#include<cstdlib>
using namespace std;
class sort
{
        int a[20];
        int n,t;
        public:
                void getdata();
                void bubblesort();
                void display();
};
void sort::getdata()
{
        cout<<"enter the number of elements in the array\n";
        cin>>n;
        cout<<"enter the elements\n";
        for(t=0;t<n;t++)
                cin>>a[t];
}
void sort::bubblesort()
{
        for(int i=0;i<n-1;i++)
        {
                for(int j=0;j<n-1-i;j++)
                {
                        if(a[j]>a[j+1])
                        {
                                int temp=a[j];
                                a[j]=a[j+1];
                                a[j+1]=temp;
                        }
                }
        }
}
void sort::display()
{
        cout<<"the sorted list is\n";
        for(int i=0;i<n;i++)
        {
                cout<<a[i]<<"\t";
        }
}
int main()
{
        sort ob;
        int op;
        while(1)
        {
                cout<<"\nenter the option\n";
                cout<<"1.get data\n2.bubble sort\n3.display\n4.exit\n";
                cin>>op;
                switch(op)
                {
                        case 1:
                                ob.getdata();
                                break;
                        case 2:
                                ob.bubblesort();
                                break;
                        case 3:
                                ob.display();
                                break;
                        case 4:
                                exit(1);
                }
        }
}


OUTPUT:-


enter the option
1.get data
2.bubble sort
3.display
4.exit
1
enter the number of elements in the array
3
enter the elements
2
1
3

enter the option
1.get data
2.bubble sort
3.display
4.exit
2

enter the option
1.get data
2.bubble sort
3.display
4.exit
3
the sorted list is
1       2       3
enter the option
1.get data
2.bubble sort
3.display
4.exit
4

No comments:

Post a Comment