This is the first solution to move all Zero numbers to the end of an array of integers. This solution modifies the same array with all non-zero numbers moving left, and Zero numbers moved to the end.
public class MoveZerosTolast {
public static void main(String[] args) {
// TODO Auto-generated method stub
//Initialize an integer Array with a few Zero values inserted along with non-zero values
int[] numArray = {65,0,0,29,0,0,0,7,0,0,18,0};
int zerosCnt=0, arrLen=numArray.length;
System.out.println("The numbers of an Array are - Before moving 0's to end");
//Call the dispArray function to display array values
dispArray(numArray);
for (int i=0;i<arrLen;i++) {
if(numArray[i]!=0)
numArray[i-zerosCnt]=numArray[i];
else {
zerosCnt++;
if(i+1 == arrLen)
break;
else if(numArray[i+1]!=0)
numArray[i+1-zerosCnt]=numArray[i+1];
}
}
//Fill the Zero values in the backward direction of the array until zerosCnt=0
for (int j=arrLen-1;zerosCnt>0;zerosCnt--) {
numArray[j--]=0;
}
System.out.println("The numbers of an Array are - After moving 0's to end");
dispArray(numArray);
}
private static void dispArray(int[] tmpArray) {
// TODO Auto-generated method stub
System.out.print("[ ");
for (int i=0;i<tmpArray.length;i++) {
System.out.print(tmpArray[i]+" ");
}
System.out.println("]");
}
}
Output:
The numbers of an Array are - Before moving 0's to end
[ 65 0 0 29 0 0 0 7 0 0 18 0 ]
The numbers of an Array are - After moving 0's to end
[ 65 29 7 18 0 0 0 0 0 0 0 0 ]

Leave a comment