To move all negative number at right side of the array

Question - 
Given an array with n element, we have to more all negative number at the right side of the array without change order of them.
Example - 
Input : arr[] = {1, 2, -3, -4, -5, 6} , n = 6
Output : {1, 2, 6, -3, -4, -5}

Approach - 
We create two array with size one of no of positive element and second of number of negative elements. we store positive numbers in positive array and negative numbers negative array and we print the positive array first and then negative array.

Implementation - 


#include<iostream>
using namespace std;
void  print(int arr[],int n)
{
    for(int i=0;i<n;i++)
        cout<<arr[i]<<", ";
}
int calculatepositive(int arr[],int n)
{
    int pos=0;
    for(int i=0;i<n;i++)
    if(arr[i]>=0)
    pos++;
    return pos;
}
int calculatenegative(int arr[],int n)
{
    int neg=0;
    for(int i=0;i<n;i++)
    if(arr[i]<0)
    neg++;
    return neg;
}
void rearrange(int arr[],int n)
{
    int positive=calculatepositive(arr,n);
    int negative=calculatenegative(arr,n);
    int parr[positive],narr[negative];
    for(int i=0,j=0,k=0;i<n;i++){
        if(arr[i]>=0){
            parr[j]=arr[i];
            j++;
        }
        else{
            narr[k]=arr[i];
            k++;
        }
    }
    for(int i=0;i<positive;i++)
        arr[i]=parr[i];

    for(int i=positive,j=0;j<negative;j++,i++){
        arr[i]=narr[j];

    }
    
}
int main()
{
    int n;
    cout<<"Enter the number of elements : ";cin>>n;
    int arr[n];
    cout<<"enter elements : "<<endl;
    for(int i=0;i<n;i++)
        cin>>arr[i];
    rearrange(arr,n);
    print(arr,n);
    
}

Time complexity - O(n)
Extra space -O(2*n)

Comments