Monday, 9 September 2019

Java Program to Move All Zeros to the End of an Array

          In this post, we will implement a Java program to move all the zeros in a given integer array to the end of the array while maintaining the relative order of the non-zero elements.

For example:

Input:

{2, 1, 0, 3, 5, 0, 9, 0}

Output:

{2, 1, 3, 5, 9, 0, 0, 0}

package com.example.demo;

public class ZeroNonZerosSeparate {
 
          public static void main(String[] args) {
  
                   int[] nums = {2,1,0,3,5,0,9,0};
  
                   int index = 0;
                   
                   for (int i = 0; i<nums.length; i++) {
                         if (nums[i] != 0) {
                                nums[index] = nums[i];
                                index++;
                         }
                   }
  
                   while (index < nums.length) {
                          nums[index] = 0;
                          index++;
                   }
  
                   for (int i = 0; i<nums.length; i++) {
                          System.out.print(nums[i]+" ");
                   }
           }

 }

Output:-
2 1 3 5 9 0 0 0 

No comments:

Post a Comment