Laboratory test -1 solutions

PROBLEM NO:4
PROBLEM DESCRIPTION:
Rearrange an array in order – smallest, largest, 2nd smallest, 2nd largest, ..
Given an array of integers, task is to print the array in the order – smallest number, Largest number, 2nd smallest number, 2nd largest number, 3rd smallest number, 3rd largest number and so on….. Examples:
Input :arr[] = [5, 8, 1, 4, 2, 9, 3, 7, 6]
Output :arr[] = {1, 9, 2, 8, 3, 7, 4, 6, 5}

SOLUTION:

#include <iostream>
using namespace std;
int main()
{
    int n,i,temp;
    static int j;
    cout<<"enter the number of elements";
    cin>>n;
    int a[n],b[n];
    cout<<"enter the array elements";
    for(i=0;i<n;i++)
    {
        cin>>a[i];
 }
    for(i=0;i<n;i++)
    {
        cout<<" "<<a[i];
    }

    cout<<endl<<"sorted array is"<<endl;
    for(i=0;i<n;i++)
    {
        for(j=i;j<n;j++)
        {
            if(a[i]>a[j])
            {
                temp=a[i];
                a[i]=a[j];
                a[j]=temp;
            }
        }
    }
    for(i=0;i<n;i++)
    {
        cout<<" "<<a[i];
    }
    cout<<endl;
    for(i=0;i<n;i++)
    {
        b[i]=0;
    }
    static int val=0;
    static int val1=(n-1);
    for(i=0;i<n;i++)
    {
        for(j=val;j<=((n-1)/2);j++)
        {
            b[i]=a[j];
            break;
        }i++;val++;
    }
for(i=1;i<n;i++)
{
    for (j=val1;j>=((n-1)/2);j++)
    {
        b[i]=a[j];
        break;
    }i++;val1--;
}
    for(i=0;i<n;i++)
    {
        cout<<" "<<b[i];
    }
   return 0;

}


Comments