move all -ve no to front

 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.

Examples : 

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

Note: Order of elements is not important here.






#include <iostream>

using namespace std;




int main()

{

    int n;

    cin>>n;

    int arr[n];

    for(int i=0;i<n;i++){

        cin>>arr[i];

    }

    int arr1[n];

    int arr2[n];

    //int n=sizeof(arr)/sizeof(int);

    int count=0;

    cout<<n<<endl;

    for(int i=0;i<n;i++){

        cout<<arr[i]<<" ";

    }

    cout<<endl;

    int k=0,m=0;

    for(int i=0;i<n;i++){

        if(arr[i]<0){

            

            arr1[k]=arr[i];

            k++;

            count++;

        }

        else if(arr[i]>=0){

            

            arr2[m]=arr[i];

            m++;

        }

    }

    for(int i=0;i<count;i++){

        arr[i]=arr1[i];

    }

    for(int i=count;i<n;i++){

        arr[i]=arr2[i-count];

    }

    for(int i=0;i<n;i++){

        cout<<arr[i]<<" ";

    }

    cout<<endl;

    


    return 0;

}

////////optimized but order not maintained/////////



#include <iostream>
using namespace std;



int main()
{
    int n;
    cin>>n;
    int arr[n];
    for(int i=0;i<n;i++){
        cin>>arr[i];
    }
    int left=0;
    int right=n-1;
    while(left<=right){
        if(arr[left]<0 && arr[right]<0){
            left++;
        }
        else if(arr[left]>0 && arr[right]<0){
            arr[left]=arr[left]^arr[right];
            arr[right]=arr[left]^arr[right];
            arr[left]=arr[left]^arr[right];
            right--;
            left++;
        }
        else if(arr[left]>0 && arr[right]>0){
            right--;
        }
        else{
            left++;
            right--;
        }
    }
    for(int i=0;i<n;i++){
        cout<<arr[i]<<" ";
    }
}

Comments

Popular posts from this blog

Sum of Even Numbers till N

Find the Runner-Up Score!

Print All Substrings