Breaking

Sunday, 9 July 2017

Sort - Odd & Even Ascending (Id-2964)

             Sort - Odd & Even Ascending

An array of N numbers is passed as the input. The program must sort the odd numbers and even numbers separately in ascending order. The odd and even numbers must retain their original odd even slots in the input.

 Input Format:
The first line contains N indicating the count of numbers in the array.
The second line contains the N array elements separated by a space.

Output Format:
The first line contains the N sorted array elements separated by a space.

Boundary Conditions:
2 <= N <= 100

Example Input/Output 1: 
Input:
9 169 181 298 16 147 263 102 155 141

Output: 141 147 16 102 155 169 298 181 263

Code:

import java.util.*;
public class Hello {

    public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
int i,e=0,o=0,j,k;
int[] arr=new int[n];

for(i=0;i<n;i++)
{
   arr[i]=sc.nextInt();
   if(arr[i]%2==0)
       e++;
       else
       o++;
}
int[] even=new int[e];
int[] indexeven=new int[e];
int[] odd=new int[o];
int[] indexodd=new int[o];
int a=0,b=0;
   for(i=0;i<n;i++)
   {
   if(arr[i]%2==0)
       {
           even[a]=arr[i];
           indexeven[a]=i;
           a++;
       }
     else if(arr[i]%2==1)
       {
           odd[b]=arr[i];
           indexodd[b]=i;
           b++;
       }
}
Arrays.sort(even);
Arrays.sort(odd);
int[] res=new int[n];

for(i=0;i<n;i++)
{
for(j=0;j<e;j++)
   {
       if(indexeven[j]==i)
           res[i]=even[j];
   }
  for(k=0;k<o;k++)
  {
      if(indexodd[k]==i)
           res[i]=odd[k];
  }
}
for(int y:res )
   System.out.println(y);

}
}

No comments:

Post a Comment

Like