fork(9) download
  1. #include <iostream>
  2. #include <assert.h>
  3. using namespace std;
  4. void printArray(int arr[], int n);
  5. void rotate(int arr[],int start,int end)
  6. {
  7. int temp = arr[end];
  8. while(start < end)
  9. {
  10. arr[end] = arr[end - 1];
  11. --end;
  12. }
  13. arr[start] = temp;
  14. }
  15.  
  16. void rearrange(int arr[], int n)
  17. {
  18. int i,j;
  19. // this for loop segregate the +ve and -ve Number
  20. for(i=0,j=0;j<n;++j)
  21. {
  22. if(arr[j] < 0)
  23. {
  24. rotate(arr,i,j);
  25. ++i;
  26. }
  27. }
  28. j = 0;
  29.  
  30. // This while loop arranging +ve and -ve number
  31. if(arr[j] < 0)
  32. ++j;
  33. while(i < n && j <= i)
  34. {
  35. rotate(arr,j,i);
  36. i = i + 1;
  37. j = j + 2;
  38.  
  39. }
  40. }
  41.  
  42. void printArray(int arr[], int n)
  43. {
  44. for (int i = 0; i < n; i++)
  45. cout << arr[i] << " ";
  46. cout << endl;
  47. }
  48.  
  49.  
  50. int main()
  51. {
  52.  
  53. int arr[] = {-5, -2, 5, 2, 4, 7, 1, 8, 0, -8};
  54. int n = sizeof(arr)/sizeof(arr[0]);
  55.  
  56. cout << "Given array is \n";
  57. printArray(arr, n);
  58.  
  59. rearrange(arr, n);
  60.  
  61. cout << "Rearranged array is \n";
  62. printArray(arr, n);
  63.  
  64. return 0;
  65. }
  66.  
Success #stdin #stdout 0s 3140KB
stdin
Standard input is empty
stdout
Given array is 
-5 -2 5 2 4 7 1 8 0 -8 
Rearranged array is 
-5 5 -2 2 -8 4 7 1 8 0