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 of 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 of the array 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.

Move Non-Zero Elements to Left

here I am using Java program to move all non-zero elements followed by zero elements in the array.


import java.util.Arrays;

public class MoveNonZeroToLeft {

	public static void main(String[] args) {
		int[] arr = new int[] { 1, 0, 2, 0, 0, 3, 4 };

	public static void moveNonZeroToLeft(int[] arr) {
		int lastIndex = arr.length - 1;
		for (int index = 0; index < arr.length;) {
			if (index == lastIndex)
			if (arr[index] == 0) {
				// swap to last index
				int temp = arr[lastIndex];
				arr[lastIndex] = arr[index];
				arr[index] = temp;
			} else {


Testing the Program

Running the above program will give you the following output:

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

Source Code


Leave a Reply

Your email address will not be published. Required fields are marked *