Computer Scientists are Pretty Pessimistic

Monday, 16 May 2016

Selection Sort

Algorithm : :


for j = n to 2 by -1 do

      t 1

      for k = 2 to j do

            if ( xt < xk ) then

                  t k
      xj xt
 


CODE : :

#include <iostream>
using namespace std;
int main ()
{
    int n;
    cout<<"Enter number of elements:"<<endl;
    cin>>n;
    int arr[n+1];
    cout<<"Enter elements:"<<endl;
    for(int i=1;i<=n;i++)
        cin>>arr[i];
    for(int j=n;j>=2;j--)
    {
        int t=1;
        for(int k=2;k<=j;k++)
        {
            if(arr[t]<arr[k])
            {
                t=k;
            }
        }
        int temp=arr[j];
        arr[j]=arr[t];
        arr[t]=temp;
    }
    for(int i=1;i<=n;i++)
        cout<<arr[i]<<" ";
    return 0;
}
 

No comments:

Post a Comment