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.

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.

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.

Tags:

I am a professional Web developer, Enterprise Application developer, Software Engineer and Blogger. Connect me on Roy Tutorials | TwitterFacebook Google PlusLinkedin | Reddit

Leave a Reply

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