fork download
  1. #include<bits/stdc++.h>
  2. using namespace std;
  3.  
  4. vector<int> RearrangebySign(vector<int>A, int n){
  5.  
  6. // Define 2 vectors, one for storing positive
  7. // and other for negative elements of the array.
  8. vector<int> pos;
  9. vector<int> neg;
  10.  
  11. // Segregate the array into positives and negatives.
  12. for(int i=0;i<n;i++){
  13.  
  14. if(A[i]>0) pos.push_back(A[i]);
  15. else neg.push_back(A[i]);
  16. }
  17.  
  18. // If positives are lesser than the negatives.
  19. if(pos.size() < neg.size()){
  20.  
  21. // First, fill array alternatively till the point
  22. // where positives and negatives ar equal in number.
  23. for(int i=0;i<pos.size();i++){
  24.  
  25. A[2*i] = pos[i];
  26. A[2*i+1] = neg[i];
  27. }
  28.  
  29. // Fill the remaining negatives at the end of the array.
  30. int index = pos.size()*2;
  31. for(int i = pos.size();i<neg.size();i++){
  32.  
  33. A[index] = neg[i];
  34. index++;
  35. }
  36. }
  37.  
  38. // If negatives are lesser than the positives.
  39. else{
  40.  
  41. // First, fill array alternatively till the point
  42. // where positives and negatives ar equal in number.
  43. for(int i=0;i<neg.size();i++){
  44.  
  45. A[2*i] = pos[i];
  46. A[2*i+1] = neg[i];
  47. }
  48.  
  49. // Fill the remaining positives at the end of the array.
  50. int index = neg.size()*2;
  51. for(int i = neg.size();i<pos.size();i++){
  52.  
  53. A[index] = pos[i];
  54. index++;
  55. }
  56. }
  57. return A;
  58.  
  59. }
  60.  
  61. int main() {
  62.  
  63. // Array Initialisation.
  64. int n = 6;
  65. vector<int> A {1,2,-4,-5,3,4};
  66.  
  67. vector<int> ans = RearrangebySign(A,n);
  68.  
  69. for (int i = 0; i < ans.size(); i++) {
  70. cout << ans[i] << " ";
  71. }
  72.  
  73. return 0;
  74. }
Success #stdin #stdout 0.01s 5280KB
stdin
Standard input is empty
stdout
1 -4 2 -5 3 4