fork download
  1. public class Main {
  2.  
  3. public static void main(String args[]) {
  4. int[] a = new int[]{6, 0, 8, 2, 3, 0, 4, 0, 1};
  5. moveZerosToEnd(a);
  6. for (int c : a) {
  7. System.out.print(c + " ");
  8. }
  9. }
  10.  
  11. private static void moveZerosToEnd(int[] a) {
  12. int z = -1;
  13. for (int i = 0; i < a.length; i++) {
  14. int c = a[i];
  15. if (c == 0 && z == -1) {
  16. z = i;
  17. continue;
  18. }
  19. if (c != 0 && z != -1) {
  20. swap(a, i, z);
  21. z++;
  22. }
  23. }
  24. }
  25.  
  26. private static void swap(int[] a, int i, int j) {
  27. int x = a[i];
  28. a[i] = a[j];
  29. a[j] = x;
  30. }
  31. }
  32.  
Success #stdin #stdout 0.04s 4575232KB
stdin
Standard input is empty
stdout
6 8 2 3 4 1 0 0 0