This is the second solution to move all Zero numbers to the end of an array of integers. This solution uses the temporary array. The resultant array has all non-zero numbers moved left, and all Zero numbers moved to the end.
public class MoveZerosToLastUsingTmpArray {
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 = {0,85,0,6,0,42,0,31,0,18,0,0};
int zerosCnt=0, idx=0, arrLen=numArray.length;
int[] tmpArray = new int[arrLen];
System.out.println("The numbers of an Array are - Before moving 0's to end");
//Call the dispArray function to display the actual array values
dispArray(numArray);
for (int i=0;i<arrLen;i++) {
if(numArray[i]!=0)
tmpArray[idx++]=numArray[i];
else
zerosCnt++;
}
//Fill the Zero values in tmpArray in forward direction until zerosCnt=0
for (;zerosCnt>0;zerosCnt--) {
tmpArray[idx++]=0;
}
//Call the dispArray function to display the tmpArray values
System.out.println("The numbers of the temp Array are - After moving 0's to end");
dispArray(tmpArray);
}
private static void dispArray(int[] varArray) {
// TODO Auto-generated method stub
System.out.print("[ ");
for (int i=0;i<varArray.length;i++) {
System.out.print(varArray[i]+" ");
}
System.out.println("]");
}
}
Output:
The numbers of an Array are - Before moving 0's to end
[ 0 85 0 6 0 42 0 31 0 18 0 0 ]
The numbers of the temp Array are - After moving 0's to end
[ 85 6 42 31 18 0 0 0 0 0 0 0 ]

Leave a comment