Move all zeros in an array to the end while keeping the order of the non-zero elements, in place.
Solution
Main.java
import java.util.Arrays;
public class Main {
static void moveZeros(int[] a) {
int pos = 0;
for (int x : a) if (x != 0) a[pos++] = x; // compact non-zero values to the front
while (pos < a.length) a[pos++] = 0; // fill the rest with zeros
}
public static void main(String[] args) {
int[] a = {0, 5, 0, 3, 12, 0, 7};
moveZeros(a);
System.out.println(Arrays.toString(a));
int[] b = {0, 0, 1};
moveZeros(b);
System.out.println(Arrays.toString(b));
}
}
Output Verified by compiling and running
[5, 3, 12, 7, 0, 0, 0]
[1, 0, 0]
Reading with for-each while writing to an index behind it is safe: the write position never overtakes the read position.
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!
We use Google Analytics cookies to see how LearnFrenzy is used and make it better, and Google AdSense to keep it free.
No analytics or ad cookies are set until you accept. Privacy Policy
·
Discussion & Comments 0
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!