Write a class ReorderArray with a public method reorder that takes one parameter arr of type int[] and returns the arr such that all even numbers in the array come to the 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 even numbers in the array come to the front of the arr.

Assumptions:

  1. arr is never null

Here is an example:

Enter no of elements in the array:
6
Enter elements in the array seperated by space:
3 5 6 4 2 4
6
4
2
4
3
5

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 array:");
		int n = s.nextInt();
		int[] arr = new int[n];
		System.out.println("Enter elements in the array seperated by space:");
		for(int i = 0; i < n; i++)
	    {
			arr[i] = s.nextInt();
        }
        ReorderArray reArr = new ReorderArray();
        int[] result = reArr.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 temp=0,count=0;
			
			for(int i = 0; i < size; i++){
				if(arr[i]%2==0){
					
					for(int j=i; j > count; j--){
						temp = arr[j-1];
						arr[j-1] = arr[j];
						arr[j] = temp;
					}
					count++;
				}
			}
			
			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 *