Alternate Sorting of Numbers

 Alternate Sorting of Numbers

PROBLEM STATEMENT :

Given an array of integers, rearrange the array in such a way that the first element is first maximum and second element is first minimum. The third element must be second maximum and fourth element must be second minimum and so on. 

Input Format: 
The first line will contain the numbers separated by a space. 

Boundary Conditions: 
Length of the input string will be from 3 to 200. 

Output Format: 
The numbers separated by a single space as per the mentioned conditions. 


Example Input/Output 1: 
Input: () 
2 3 4 7
Output: 7 2 4 3

Example Input/Output 2: 
Input: () 
1 2 3 4 5 6 7 
Output: 7 1 6 2 5 3 4

Example Input/Output 3: 
Input: () 
23 55 
Output: 55 23



SOLUTION :

C (Programming Language)


      

#include<stdio.h> #include<stdlib.h> int fun(const void *a,const void *b) { return (*(int*)a - *(int*)b); } int main() { int n=-1,a[201],i; while(scanf("%d ",&a[++n])==1); qsort(a,n,sizeof(a[0]),fun); //qsort function from stdlib for(i=0;i<n/2;++i) { printf("%d %d ",a[n-i-1],a[i]); } if(n%2==1) printf("%d",a[n/2]); }



C++ (CPP)

       

#include <iostream> #include<algorithm> using namespace std; int main(int argc, char** argv) { int n=-1,a[201],i; while(cin>>a[++n]); sort(a,a+n); for(i=0;i<n/2;++i) { cout<<a[n-i-1]<<" "<<a[i]<<" "; } if(n%2==1) cout<<a[n/2]; }



JAVA

       

import java.util.*; public class Hello { public static void main(String[] args) { Scanner sc=new Scanner(System.in); int[] a=new int[201]; int n=0,i; while(sc.hasNext()) { a[n++]=sc.nextInt(); } Arrays.sort(a,0,n); for(i=0;i<n/2;++i) { System.out.print(a[n-i-1]+" "+a[i]+" "); } if(n%2==1) System.out.print(a[n/2]); } }



PYTHON

       

l=sorted(list(map(int,input().split()))) length=len(l) for i in range(length//2): print(l[length-i-1],l[i],end=' ') if length%2!=0: print(l[length//2])



Never Stop Learning !!


Comments

Popular posts from this blog

DP (1) - Count number of ways to cover a distance

Zero Insert After K Times One

Left Number Twice Right