Question -
Given an array which may contain 0, our task is to move all zeros at right side without change the order or other elements
Example -
Input : {10,20,0,1,0,2}
Output : {10,20,1,2,0,0}
Input : {10,22}
Output : {10,22}
Approach -
We solve this problem with the help of a temporary array.
Implementation -
#include<iostream>
using namespace std;
void print(int ar[],int n)
{
for(int i=0;i<n;i++)
cout<<ar[i]<<" ";
}
void movezeros(int arr[],int n)
{
int ar[n];
int numofzero=0;
for(int i=0,j=0;i<n;i++){
if(arr[i]!=0){
ar[j]=arr[i];
j++;
}
if(arr[i]==0)
numofzero++;
}
for(int i=(n-numofzero);i<n;i++)
ar[i]=0;
print(ar,n);
}
int main()
{
int n;
cout<<"Enter the number of elements : ";cin>>n;
cout<<"Enter the numbers : "<<endl;
int arr[n];
for(int i=0;i<n;i++)
cin>>arr[i];
movezeros(arr,n);
return 0;
}
Time complexity - O(n+d)
where d is the no of zeros in array
Comments
Post a Comment