Saturday 22 October 2011

Program on Selection Sort


#include<iostream>
#include<cstdlib>
using namespace std;
class sort
{
        int a[20];
        int n,t;
        public:
                void getdata();
                void selectionsort();
                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::selectionsort()
{
        int small;
        for(int i=0;i<n-1;i++)
        {
                small=i;
                for(int j=i+1;j<n;j++)
                {
                        if(a[small]>a[j])
                        small=j;
                }
                int temp=a[i];
                a[i]=a[small];
                a[small]=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.selection sort\n3.display\n4.exit\n";
                cin>>op;
                switch(op)
                {
                        case 1:
                                ob.getdata();
                                break;
                        case 2:
                                ob.selectionsort();
                                break;
                        case 3:
                                ob.display();
                                break;
                        case 4:
                                exit(1);
                }
        }
}



OUTPUT:-

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

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

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

No comments:

Post a Comment