- Given an array containing integers (+ve, -ve & 0), we would like to move zeros to end of array.
- We will iterate through the array & we will move zeros to end of array.
- We have discussed similar problems:
- Segregate array containing even & odd numbers.
- Dutch national flag problem or sort array containing 0, 1 & 2
1. Example – move zeros to end of array in java (example)
Example 1:
- If input array is { 2, 0, 5, 2, 0, 3, 1 }
- We would like to get output {2, 5, 2, 3, 1, 0, 0}
Example 2:
- If input array is { 1, 0, 2, 3, 0, 4, 0}
- We would like to get output {1, 2, 3, 4, 0, 0, 0}
2. Algorithm – move zeros to end of array in java (example)
- Initialize variable nonZeros=0
- nonZeros represents number of non zero element in an array
- Iterate through the array ( 0 to length of array).
- if current element is non zero i.e. inputArray[i] != 0
- inputArray[nonZeros++] = inputArray[index];
- if current element is non zero i.e. inputArray[i] != 0
- At end of iteration, all non zero elements are moved to left side of array.
- We will append zeros till the length of array.
- Now, we have successfully move all zeros to end of array.
- Time complexity of algorithm is O (n).
3. Program – move zeros to the end of array in java (example)
package org.learn.arrays; import java.util.Arrays; public class MoveZerosToEnd { private static void moveZeroToEnd( int [] inputArray) { int index = 0 ; int nonZeros = 0 ; int length = inputArray.length; while (index < length) { if (inputArray[index] != 0 ) { inputArray[nonZeros++] = inputArray[index]; } index++; } while (nonZeros < length) { inputArray[nonZeros++] = 0 ; } System.out.printf( "%s" , Arrays.toString(inputArray)); } public static void main(String[] args) { int arr[] = { 2 , 0 , 5 , 2 , 0 , 3 , 1 }; String sArray = Arrays.toString(arr); System.out.printf( "1. Move zeros of array %s to end :" , sArray); moveZeroToEnd(arr); arr = new int []{ 1 , 0 , 2 , 3 , 0 , 4 , 0 }; sArray = Arrays.toString(arr); System.out.printf( "\n2. Move zeros of array %s to end :" , sArray); moveZeroToEnd(arr); } } |
4. Output – move zeros to the end of array in java (example)
1. Move zeros of array [2, 0, 5, 2, 0, 3, 1] to end :[2, 5, 2, 3, 1, 0, 0] 2. Move zeros of array [1, 0, 2, 3, 0, 4, 0] to end :[1, 2, 3, 4, 0, 0, 0] |