Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class Ex7 {
- // Write a Java program to move all 0's to the end of an array. Maintain the
- // relative order of the other (non-zero) array elements.
- public static void main(String[] args) {
- System.out.println("First Solution:");
- first();
- System.out.println("\nSecond Solution:");
- second();
- }
- public static void first() {
- int[] arr = { 2, 0, 9, 8, 0, 7, 6, 3, 0, 0, 2, 9 };
- // first solution
- int[] resArr = new int[arr.length];
- int c = 0;
- // copy not zero numbers
- for (int i = 0; i < arr.length; i += 1) {
- if (arr[i] != 0) {
- resArr[c] = arr[i];
- c += 1;
- }
- }
- // fill zero
- for (int i = c; i < resArr.length; i += 1) {
- resArr[i] = 0;
- }
- // print the result
- for (int i = 0; i < resArr.length; i += 1) {
- System.out.print(resArr[i] + " ");
- }
- }
- public static void second() {
- int[] arr = { 2, 0, 9, 8, 0, 7, 6, 3, 0, 0, 2, 9 };
- // first solution
- int[] resArr = new int[arr.length];
- int c = 0;
- int z = resArr.length - 1;
- // copy not zero numbers
- for (int i = 0; i < arr.length; i += 1) {
- if (arr[i] != 0) {
- resArr[c] = arr[i];
- c += 1;
- } else {
- resArr[z] = 0;
- z -= 1;
- }
- }
- // print the result
- for (int i = 0; i < resArr.length; i += 1) {
- System.out.print(resArr[i] + " ");
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement