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
Thank you for visting the blog.
Related Posts:-
1) Difference between NoClassDefFoundError and ClassNotFoundException in Java
2) Swap two variables without using third variable in Java
3) Sort a binary array using one traversal in Java
4) Java program to find second largest number in an array
5) Java Code to Print the Numbers as Pyramid - Examples
6) Java Program to find the Missing Number in an Array
7) Java program to print the first n prime numbers
8) Write a Java program to print the Floyd's triangle
Related Posts:-
1) Difference between NoClassDefFoundError and ClassNotFoundException in Java
2) Swap two variables without using third variable in Java
3) Sort a binary array using one traversal in Java
4) Java program to find second largest number in an array
5) Java Code to Print the Numbers as Pyramid - Examples
6) Java Program to find the Missing Number in an Array
7) Java program to print the first n prime numbers
8) Write a Java program to print the Floyd's triangle
No comments:
Post a Comment