Question -
move all negative elements to end in order with extra space allowed
Example -
Input : arr[] = {1, 2, -3, 4, 5, -6}
Output : {1, 2, 4, 5, -3, -6}
Approach -
first we create a temporary array with size of size of first array. now first we store positive elements of array in temporary and then store negative elements.
Implementation -
#include<iostream>
using namespace std;
void movenegative(int arr[],int n)
{
int temp[n];
int j=0;
for(int i=0;i<n;i++){
if(arr[i]>0){
temp[j]=arr[i];
j++;
}
}
for(int i=0;i<n;i++){
if(arr[i]<0){
temp[j]=arr[i];
j++;
}
}
for(int i=0;i<n;i++)
cout<<temp[i]<<", ";
}
int main()
{
int n;
cout<<"Enter number of elements : ";cin>>n;
int arr[n];
cout<<"Enter elements : ";
for(int i=0;i<n;i++)
cin>>arr[i];
movenegative(arr,n);
return 0;
}
Time complexity - O(2*n)
Extra space - O(2*n)
Comments
Post a Comment