To move all zeros at the right side of the array without changing the order of elements of the array

Question - 
Given an sorted or unsorted array, your task is to move all zeros of the array at the right side of the array without changing the order of the elements of array.
Example  -
Input : arr[] = {1, 2, 3, 0, 5, 2, 0, 0, 4, 5}
Output : {1, 2, 3, 5, 2, 4, 5, 0, 0, 0, 0}
Approach - 
we reinitilize the array with non zeros elements first and after that we store zeros in remaining place.

Implementation - 
//move zero at end of array without chamge order
#include<iostream>
using namespace std;
void movezero(int arr[],int n)
{
int j=0;
for(int i=0;i<n;i++){
if(arr[i]!=0){
arr[j++]=arr[i];
}
}
while(j<n)
arr[j++]=0;
}
void print(int arr[],int n)
{
for(int i=0;i<n;i++)
cout<<arr[i]<<" ";
}
int main()
{
int n;
cout<<"Enter n : ";
cin>>n;
int arr[n];
cout<<"Enter values : "<<endl;
for(int i=0;i<n;i++)
cin>>arr[i];
movezero(arr,n);
print(arr,n);
}
Extra space  - O(1)

Comments