Given an unsorted array arr[] of size N having both negative and positive integers. The task is place all negative element at the end of array without changing the order of positive element and negative element.
Input Format
The first line of the input represent an integer of Size N The next line represents unsorted array with both positive and negative numbers separated by space
Constraints
1 ≤ N ≤ 10^5 -10^5 ≤ arr[] ≤ 10^5
Output Format
The output line prints all negative element at the end of array without changing the order of positive element and negative element separated by space
Sample Input 0
8
1 -1 3 2 -7 -5 11 6
Sample Output 0
1 3 2 11 6 -1 -7 -5
Program :
#include <bits/stdc++.h>
using namespace std;
void segregate_elements(int n,vector<int> &arr)
{
vector<int> temp;
for(int i=0;i<n;i++)
{
if(arr[i]>=0) temp.push_back(arr[i]);
}
for(int i=0;i<n;i++)
{
if(arr[i]<0) temp.push_back(arr[i]);
}
for(int i=0;i<n;i++)
{
arr[i]=temp[i];
}
return;
}
int main()
{
int n;
cin>>n;
vector<int> arr(n);
for(int i=0;i<n;i++)
{
cin>>arr[i];
}
segregate_elements(n,arr);
for(int i=0;i<n;i++)
{
cout<<arr[i]<<" ";
}
return 0;
}
0 Comments