fork download
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4. vector<int> rearrangeArray(vector<int>& a) {
  5. int n = a.size();
  6. vector<int>ans(2*n+1,1e9);
  7. int pos=0,neg=1;
  8. for(int i=0;i<n;i++){
  9. if(a[i]>0){
  10. ans[pos] = a[i];
  11. a[i]=1e9;
  12. pos=pos+2;
  13. }
  14. else{
  15. ans[neg] = a[i];
  16. a[i]=-1e9;
  17. neg = neg+2;
  18. }
  19. }
  20.  
  21. //adjusting the remaining elements
  22. int idx=-1;int count=0;
  23. for(int i=0;i<ans.size();i++){
  24. if(ans[i]!=1e9 && idx>=0){
  25. swap(ans[idx],ans[i+1]);
  26. idx=i+1;
  27. }
  28. else{
  29. idx=i;
  30. }
  31. }
  32. for(int i=0;i<ans.size();i++)
  33. cout<<ans[i]<<" ";
  34.  
  35. return ans;
  36. }
  37. int main() {
  38. vector<int>a = {1,20,21,22,23,3,2,5,4,-11,-12};
  39. vector<int>v = rearrangeArray(a);
  40. return 0;
  41. }
Success #stdin #stdout 0.01s 5312KB
stdin
Standard input is empty
stdout
20 -11 -12 21 1000000000 22 1000000000 23 1000000000 3 1000000000 2 1000000000 5 1000000000 4 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 0