Program to place all zeros in the end of the array
This post will help you in understanding how to place all the zeros in the end of an unsorted array. The logic is like this - whenever you encounter a non zero element increment the counter and check if the counter less than the traversed position. If counter is less than the traversed position, copy the element from traversed position to the position of counter in the array.
Complexity - O(n).
The program is as follows -
Complexity - O(n).
The program is as follows -
public class arrayzero {
public static void main(String args[])
{
int arr[] = {15,2,5,1,0,5,6,0,0,3,7,9,0,0,66,7,0,3,0,-1,2,0};
zerolast(arr);
System.out.println(" Modified array = ");
for(int i=0;i<arr.length;i++)
{
System.out.print(arr[i] + " ");
}
}
public static void zerolast(int arr[])
{
int index=-1;
for(int i=0; i<arr.length;i++)
{
if(arr[i]!=0)
{
index++;
if(i>index)
{
arr[index]=arr[i];
}
}
}//end of for
for(int j =index+1;j<arr.length;j++)
{
arr[j]=0;
}
}
}
Comments
Post a Comment