#include<bits/stdc++.h>
using namespace std;
vector<int> RearrangebySign(vector<int>A, int n){
// Define 2 vectors, one for storing positive
// and other for negative elements of the array.
vector<int> pos;
vector<int> neg;
// Segregate the array into positives and negatives.
for(int i=0;i<n;i++){
if(A[i]>0) pos.push_back(A[i]);
else neg.push_back(A[i]);
}
// If positives are lesser than the negatives.
if(pos.size() < neg.size()){
// First, fill array alternatively till the point
// where positives and negatives ar equal in number.
for(int i=0;i<pos.size();i++){
A[2*i] = pos[i];
A[2*i+1] = neg[i];
}
// Fill the remaining negatives at the end of the array.
int index = pos.size()*2;
for(int i = pos.size();i<neg.size();i++){
A[index] = neg[i];
index++;
}
}
// If negatives are lesser than the positives.
else{
// First, fill array alternatively till the point
// where positives and negatives ar equal in number.
for(int i=0;i<neg.size();i++){
A[2*i] = pos[i];
A[2*i+1] = neg[i];
}
// Fill the remaining positives at the end of the array.
int index = neg.size()*2;
for(int i = neg.size();i<pos.size();i++){
A[index] = pos[i];
index++;
}
}
return A;
}
int main() {
// Array Initialisation.
int n = 6;
vector<int> A {1,2,-4,-5,3,4};
vector<int> ans = RearrangebySign(A,n);
for (int i = 0; i < ans.size(); i++) {
cout << ans[i] << " ";
}
return 0;
}
I2luY2x1ZGU8Yml0cy9zdGRjKysuaD4KdXNpbmcgbmFtZXNwYWNlIHN0ZDsKCiAgdmVjdG9yPGludD4gUmVhcnJhbmdlYnlTaWduKHZlY3RvcjxpbnQ+QSwgaW50IG4pewogICAgCiAgLy8gRGVmaW5lIDIgdmVjdG9ycywgb25lIGZvciBzdG9yaW5nIHBvc2l0aXZlIAogIC8vIGFuZCBvdGhlciBmb3IgbmVnYXRpdmUgZWxlbWVudHMgb2YgdGhlIGFycmF5LgogIHZlY3RvcjxpbnQ+IHBvczsKICB2ZWN0b3I8aW50PiBuZWc7CiAgCiAgLy8gU2VncmVnYXRlIHRoZSBhcnJheSBpbnRvIHBvc2l0aXZlcyBhbmQgbmVnYXRpdmVzLgogIGZvcihpbnQgaT0wO2k8bj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