TechoSagar: Even and odd elements at even and odd positions

Search

Google Alert - jobs

Even and odd elements at even and odd positions

Given an array. The task is to arrange the array such that odd elements occupy the odd positions and even elements occupy the even positions. The order of elements must remain same. Consider zero-based indexing. After printing according to conditions, if remaining, print the remaining elements as it is.
Input:
The first line of input contains an integer T denoting the number of test cases. Then T test cases follow. Each test case consists of two lines. First line of each test case contains an Integer N denoting size of array and the second line contains N space separated elements.
Output:
For each test case, in a new line print the arranged array.
Constraints:
1<=T<=100
1<=N<=105

1<=A[i]<=105
Example:
Input:

2
6
1 2 3 4 5 6
4
3 2 4 1
Output:
2 1 4 3 6 5
2 3 4 1
Your Code
#include<iostream>

using namespace std;

int main()
{
int t;
cin>>t;
while(t--)
{
int n;
cin>>n;
int a[100000];
int i;
for(i=0; i<n; i++)
{
cin>>a[i];
}
int c[100000],b[100000];
int j=0,k=0;
for(i=0; i<n; i++)
{
if(a[i]%2==0)
{
c[k]=a[i];
k++;
}
else
{
b[j]=a[i];
j++;
}
}
for(i=0; i<j ||i<k; i++)
{   if(i<k)
cout<<c[i]<<" ";
if(i<j)
cout<<b[i]<<" ";
}
cout<<endl;
}
} 

Follow us

Follow Bijendra Kumar on Facebook