TechoSagar: Array of alternate +ve and -ve no.s

Search

Google Alert - jobs

Array of alternate +ve and -ve no.s

Given an unsorted array of positive and negative numbers. Create an array of alternate positive and negative numbers without changing the relative order of positive and negative numbers respectively.
Input:
The first line of input contains an integer T denoting the number of test cases.
The first line of each test case is N,N is the size of array.
The second line of each test case contains N input a[].

Output:
Print an array of alternate positive and negative numbers.
Note: Solution should start with positive number.

Constraints:
1 ≤ T ≤ 50
1 ≤ N ≤ 100
-1000 ≤ a[] ≤ 1000

Example:
Input
1
9
9 4 -2 -1 5 0 -5 -3 2
Output
9 -2 4 -1 5 -5 0 -3 2
Your code 
#include<iostream>

using namespace std;

int main()
{
int t;
cin>>t;
while(t--)
{
int i, a[1000];
int n;
cin>>n;
int p[1000], q[1000];
int x=0, y=0;
for(i=0; i<n; i++)
{
cin>>a[i];
int h=a[i];
if(h>=0)
{
p[x]=h;
//cout<<p[x]<<" ";
x++;
}
if(h<0)
{
q[y]=h;
// cout<<q[y];
y++;
}
}
for(i=0; i<x || i<y; i++)
{   
cout<<p[i]<<" ";
if(i<x && n%2==0)
{
cout<<q[i]<<" ";
}
if(i<x-1 && n%2!=0)
{
cout<<q[i]<<" ";
}
cout<<endl;
}
}

Follow us

Follow Bijendra Kumar on Facebook