fork(1) 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. for(int i=0;i<ans.size();i++)
  21. cout<<ans[i]<<" ";
  22.  
  23. //adjusting the remaining elements
  24. int idx=-1;int count=0;
  25. for(int i=0;i<ans.size();i++){
  26. if(ans[i]!=1e9 && idx>=0){
  27. swap(ans[idx],ans[i+1]);
  28. idx=i+1;
  29. }
  30. else{
  31. idx=i;
  32. }
  33. }
  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 5256KB
stdin
Standard input is empty
stdout
1 -11 20 -12 21 1000000000 22 1000000000 23 1000000000 3 1000000000 2 1000000000 5 1000000000 4 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000