School, 09.09.2017, Ex7, move zeros to the end of the array

Sep 9th, 2017
158
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
1.
2. public class Ex7 {
3.     // Write a Java program to move all 0's to the end of an array. Maintain the
4.     // relative order of the other (non-zero) array elements.
5.     public static void main(String[] args) {
6.         System.out.println("First Solution:");
7.         first();
8.         System.out.println("\nSecond Solution:");
9.         second();
10.     }
11.
12.     public static void first() {
13.         int[] arr = { 2, 0, 9, 8, 0, 7, 6, 3, 0, 0, 2, 9 };
14.
15.         // first solution
16.         int[] resArr = new int[arr.length];
17.         int c = 0;
18.
19.         // copy not zero numbers
20.         for (int i = 0; i < arr.length; i += 1) {
21.             if (arr[i] != 0) {
22.                 resArr[c] = arr[i];
23.                 c += 1;
24.             }
25.         }
26.
27.         // fill zero
28.         for (int i = c; i < resArr.length; i += 1) {
29.             resArr[i] = 0;
30.         }
31.
32.         // print the result
33.         for (int i = 0; i < resArr.length; i += 1) {
34.             System.out.print(resArr[i] + " ");
35.         }
36.     }
37.
38.     public static void second() {
39.         int[] arr = { 2, 0, 9, 8, 0, 7, 6, 3, 0, 0, 2, 9 };
40.
41.         // first solution
42.         int[] resArr = new int[arr.length];
43.         int c = 0;
44.         int z = resArr.length - 1;
45.
46.         // copy not zero numbers
47.         for (int i = 0; i < arr.length; i += 1) {
48.             if (arr[i] != 0) {
49.                 resArr[c] = arr[i];
50.                 c += 1;
51.             } else {
52.                 resArr[z] = 0;
53.                 z -= 1;
54.             }
55.         }
56.
57.         // print the result
58.         for (int i = 0; i < resArr.length; i += 1) {
59.             System.out.print(resArr[i] + " ");
60.         }
61.     }
62.
63. }
RAW Paste Data