Move all negative numbers to beginning and positive to end with constant extra space | geeksforgeeks solution | array

Move all negative numbers to beginning and positive to end with constant extra space | best solution 

 


An array contains both positive and negative numbers in random order. Rearrange the array elements so that all negative numbers appear before all positive numbers.

order of elements is not important here.

Input: -12, 11, -13, -5, 6, -7, 5, -3, -6

Output: -12 -13 -5 -7 -3 -6 11 6 5

solution :

 #include <bits/stdc++.h>

using namespace std;


void rearrange(int arr[] , int size)

{

    vector<int>negative;

    vector<int> positive;

    for(int i = 0 ; i < size ; i++)

    {

        if(arr[i] < 0)

        {

            negative.push_back(arr[i]);

        }

        else

        {

            positive.push_back(arr[i]);

        }

    }

    negative.insert(negative.end(),positive.begin(),positive.end());

    for(auto i  = negative.begin() ; i != negative.end() ; i++)

    {

        cout << *i << " ";

    }

}



int main()

{

    int arr[7] = {30,67,23 -4, -3 ,24 , -2};

    int size = sizeof(arr)/sizeof(arr[0]);

    rearrange(arr, size);

    

}


Comments