Write a class ReorderArray with a public method reorder that takes one parameter arr of type int[] and returns the arr such that all zeros should come in front of the arr

Write a class ReorderArray with a public method reorder that takes one parameter arr of type int[] and returns the arr such that all zeros should come in front of the arr.

Assumptions:

  1. arr is never null

Here is an example:

Enter no of elements in the arr:
8
Enter elements in the arr seperated by space:
55 0 21 0 63 0 45 0
0
0
0
55
21
63
45

Solution

import java.util.Scanner;
public class ReorderArrayMain{
	public static void main(String[] args){
		Scanner s = new Scanner(System.in);
		System.out.println("Enter no of elements in the arr:");
		int n = s.nextInt();
		int[] arr = new int[n];
		System.out.println("Enter elements in the arr seperated by space:");
		for(int i = 0; i < n; i++)
	    {
			arr[i] = s.nextInt();
	    }
	    ReorderArray rOrder = new ReorderArray();
	    int[] result = rOrder.reorder(arr);
	    for(int j = 0; j < result.length; j++) {
	    System.out.println(result[j]);
	    }
	}

	public int[] reorder(int[] arr) {
		//Write your code here
		
		int size = arr.length;
		int i = size-1, j=size-1;
		
		while(i >= 0){
			if(arr[i] != 0){
				arr[j] = arr[i];
				j--;
			}
			i--;
		}
		
		while(j >= 0){
			arr[j] = 0;
			j--;
		}
		
		return arr;
		
	}
}

Happy Learning – If you require any further information, feel free to contact me.

Share your love
Saurav Hathi

Saurav Hathi

I'm currently studying Bachelor of Computer Science at Lovely Professional University in Punjab.

πŸ“Œ Nodejs and Android 😎
πŸ“Œ Java

Articles: 444

Leave a Reply

Your email address will not be published. Required fields are marked *