Learn-dsa..in 30 days!



























CC-6 : Move zeros in array to end indices of array.

Description:

Given an input integer array arr, find all zeros and move the same to end indices of the array.

Test cases and expected outputs:

Input Parameters Expected outputs
arr={5,0,7,0,9,0} 5,7,9,0,0,0
arr={0,0,7,0,0,0} 7,0,0,0,0,0
arr={0,0,0,0,0,0} 0,0,0,0,0,0
arr={9,8,7,6,5,4} 9,8,7,6,5,4

Pseudocode:

The java method should accept following input parameters: arr (int array).
Start a for loop that iterates backwards from last index of arr to first index using loop variable idx:
If value at arr[idx] is 0, we need to move it to end of arr:
Initialize currIndex int variable to idx.
Start a while loop that iterates forward from currIndex to arr.length-1, or till we reach a zero at currIndex+1:
Keep interchanging the value of array element at index currentIdx and currentIdx+1. This way the zero we found above in if statement starts moving towards end of arr.
After the while loop and for loop end, return arr, it now has all zeros moved to end indices.

Code:

public static int[] arrayMoveZerosToEndOfArray(int[] arr) throws Exception{
	int idx=0;
	for (idx=arr.length-1; idx>=0; idx--) {
		if (arr[idx] == 0) {
			int currIndex=idx;
			while ((currIndex !=arr.length-1) && (arr[currIndex+1]!=0)){
				int temp=arr[currIndex+1];
				arr[currIndex+1]=arr[currIndex];
				arr[currIndex]=temp;
				currIndex++;
			}
		}
	}
	return arr;
}

Click here to download and run code and test cases !