Sunday, 10 December 2017

Alternate sorting


   Alternate sorting is a problem of testing the knowledge of using loops and conditional statements. 

Problem:

           Given an array of integers,rearrange the array in such a way that first element is 
first maximum and the second element is 
first minimum.
   Eg:
        Input:  1,2,3,4,5,6,7
        Output: 7,1,6,2,5,3,4

Program:


#include<iostream>
using namespace std;
int main()
{
    int arr[50],n,i,j;
    cin>>n;
    for(i=0;i<n;i++)
    {
        cin>>arr[i];
    }
    for(i=0;i<n-1;i++)
    {
        for(j=i;j<n;j++)
        {
            if(i%2==0)
            {
               if(arr[i]<arr[j])
                {
                    int temp=arr[i];
                    arr[i]=arr[j];
                    arr[j]=temp;
                }
            }
            else
            {
                if(arr[i]>arr[j])
                {
                     int temp=arr[i];
                      arr[i]=arr[j];
                      arr[j]=temp;
                }
            }
        }
    }
    for(i=0;i<n;i++)
    {
        cout<<arr[i]<<endl;
    }
}

Output:


No comments:

Post a Comment