Sunday, 2 September 2012

Selection sort


#include<iostream.h>
#include<conio.h>

class selection
{
private:
    int a[10],n;
public:
    void read();
    void sort();
    void show();
};

void selection::read()
{
    cout<<"Enter how many elements you want to sort : ";
    cin>>n;
    cout<<"Enter "<<n<<" elements to sort : ";
    for(int i=0;i<n;i++)
        cin>>a[i];
}

void selection::sort()
{
    int small,temp;
    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;
        }
        if(i!=small)
        {
         temp=a[i];
         a[i]=a[small];
         a[small]=temp;
        }
    }
}

void selection::show()
{
    cout<<"Sorted elements are : ";
    for(int i=0;i<n;i++)
        cout<<a[i]<<" ";
}

void main()
{
    clrscr();
    selection s;
    s.read();
    s.sort();
    s.show();
    getch();
}

No comments:

Post a Comment