Move Non-Zero Array Elements to Left using Java

This examples shows how to move all non-zero elements (if any) in an array to the left and all zero elements to the right in the array using Java.

Your integer array may hold zero (0) and non-zero (1, 2, 4, etc.) elements. You have a requirement to have all non-zero elements first followed by 0 elements in the array. So this example helps you how to do it.

Logic of algorithm

Iterate through the array elements from the beginning one by one and if you find 0 then swap that element with the non-zero element from the end index of the array and accordingly increase the begin array index or decrease the end array index. Repeat this process until the required elements are swapped.

Source code

import java.util.Arrays;
public class MoveNonZeroToLeft {
	public static void main(String[] args) {
		int[] arr = new int[] { 1, 0, 2, 0, 0, 3, 4 };
		System.out.println(Arrays.toString(arr));
		moveNonZeroToLeft(arr);
	}
	public static void moveNonZeroToLeft(int[] arr) {
		int lastIndex = arr.length - 1;
		for (int index = 0; index < arr.length;) {
			if (index == lastIndex)
				break;
			if (arr[index] == 0) {
				// swap to last index
				int temp = arr[lastIndex];
				arr[lastIndex] = arr[index];
				arr[index] = temp;
				lastIndex--;
			} else {
				index++;
			}
		}
		System.out.println(Arrays.toString(arr));
	}
}

Output

[1, 0, 2, 0, 0, 3, 4]
[1, 4, 2, 3, 0, 0, 0]

Thanks for reading.

Leave a Comment