1. Introduction
Given an array of integers, the task is to move all zeros present in the array to the end without changing the order of non-zero elements. This is a common problem in array manipulations and tests the understanding of in-place array modifications.
2. Program Steps
1. Initialize a variable position to 0. This will help in placing the non-zero numbers at the correct positions in the array.
2. Traverse the array from start to end.
3. For each element, if the element is non-zero, place it at the position index and increment the position.
4. After the traversal, fill all the remaining positions in the array with 0’s till the end.
3. Code Program
public class MoveZerosToEnd {
public static void moveZeros(int[] arr) {
int n = arr.length;
int position = 0;
// Move all non-zero elements to the front
for (int i = 0; i < n; i++) {
if (arr[i] != 0) {
arr[position++] = arr[i];
}
}
// Fill the remaining positions with zeros
while (position < n) {
arr[position++] = 0;
}
}
public static void main(String[] args) {
int[] arr = {6, 0, 8, 2, 3, 0, 4, 0, 1};
moveZeros(arr);
for (int i : arr) {
System.out.print(i + " ");
}
}
}
Output:
6 8 2 3 4 1 0 0 0
4. Step By Step Explanation
1. The function moveZeros modifies the input array by moving all zeros to the end.
2. It uses a position variable to keep track of the location where the next non-zero number should be placed.
3. As the array is traversed, non-zero numbers are placed in their correct position and the position is incremented.
4. After all non-zero numbers are placed correctly, the remaining positions in the array are filled with zeros.
5. The main function demonstrates the process using the array {6, 0, 8, 2, 3, 0, 4, 0, 1}, and after moving zeros to the end, the modified array becomes {6, 8, 2, 3, 4, 1, 0, 0, 0}.