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;
}
Comments
Post a Comment