#include <iostream>
#include <assert.h>
using namespace std;
void printArray(int arr[], int n);
void rotate(int arr[],int start,int end)
{
int temp = arr[end];
while(start < end)
{
arr[end] = arr[end - 1];
--end;
}
arr[start] = temp;
}
void rearrange(int arr[], int n)
{
int i,j;
// this for loop segregate the +ve and -ve Number
for(i=0,j=0;j<n;++j)
{
if(arr[j] < 0)
{
rotate(arr,i,j);
++i;
}
}
j = 0;
// This while loop arranging +ve and -ve number
if(arr[j] < 0)
++j;
while(i < n && j <= i)
{
rotate(arr,j,i);
i = i + 1;
j = j + 2;
}
}
void printArray(int arr[], int n)
{
for (int i = 0; i < n; i++)
cout << arr[i] << " ";
cout << endl;
}
int main()
{
int arr[] = {-5, -2, 5, 2, 4, 7, 1, 8, 0, -8};
int n = sizeof(arr)/sizeof(arr[0]);
cout << "Given array is \n";
printArray(arr, n);
rearrange(arr, n);
cout << "Rearranged array is \n";
printArray(arr, n);
return 0;
}
I2luY2x1ZGUgPGlvc3RyZWFtPgojaW5jbHVkZSA8YXNzZXJ0Lmg+CnVzaW5nIG5hbWVzcGFjZSBzdGQ7CnZvaWQgcHJpbnRBcnJheShpbnQgYXJyW10sIGludCBuKTsKdm9pZCByb3RhdGUoaW50IGFycltdLGludCBzdGFydCxpbnQgZW5kKQp7CiAgaW50IHRlbXAgPSBhcnJbZW5kXTsKICB3aGlsZShzdGFydCA8IGVuZCkKICB7CiAgICBhcnJbZW5kXSA9IGFycltlbmQgLSAxXTsKICAgIC0tZW5kOwogIH0KICBhcnJbc3RhcnRdID0gdGVtcDsKfQoKdm9pZCByZWFycmFuZ2UoaW50IGFycltdLCBpbnQgbikKewogICAgaW50IGksajsKICAgICAvLyB0aGlzIGZvciBsb29wIHNlZ3JlZ2F0ZSB0aGUgK3ZlIGFuZCAtdmUgTnVtYmVyCiAgICBmb3IoaT0wLGo9MDtqPG47KytqKQogICAgewogICAgICAgIGlmKGFycltqXSA8IDApCiAgICAgICAgewogICAgICAgIHJvdGF0ZShhcnIsaSxqKTsKICAgICAgICArK2k7CiAgICAgICAgfQogICAgfQogICAgaiA9IDA7CiAgICAKICAgIC8vIFRoaXMgd2hpbGUgbG9vcCBhcnJhbmdpbmcgK3ZlIGFuZCAtdmUgbnVtYmVyIAogICAgaWYoYXJyW2pdIDwgMCkKICAgICAgICArK2o7CiAgICB3aGlsZShpIDwgbiAmJiBqIDw9IGkpCiAgICB7CiAgICAgICAgcm90YXRlKGFycixqLGkpOwogICAgICAgIGkgPSBpICsgMTsKICAgICAgICBqID0gaiArIDI7CgogICAgfQp9Cgp2b2lkIHByaW50QXJyYXkoaW50IGFycltdLCBpbnQgbikKewogICAgZm9yIChpbnQgaSA9IDA7IGkgPCBuOyBpKyspCiAgICAgIGNvdXQgPDwgYXJyW2ldIDw8ICIgIjsKICAgIGNvdXQgPDwgZW5kbDsKfQoKCmludCBtYWluKCkKewogICAKICAgIGludCBhcnJbXSA9IHstNSwgLTIsIDUsIDIsIDQsIDcsIDEsIDgsIDAsIC04fTsKICAgIGludCBuID0gc2l6ZW9mKGFycikvc2l6ZW9mKGFyclswXSk7CgogICAgY291dCA8PCAiR2l2ZW4gYXJyYXkgaXMgXG4iOwogICAgcHJpbnRBcnJheShhcnIsIG4pOwoKICAgIHJlYXJyYW5nZShhcnIsIG4pOwoKICAgIGNvdXQgPDwgIlJlYXJyYW5nZWQgYXJyYXkgaXMgXG4iOwogICAgcHJpbnRBcnJheShhcnIsIG4pOwoKICAgIHJldHVybiAwOwp9Cg==