Minimum moves to segregate even followed by odd elements in Array

You may also like to read:

This tutorial will find out minimum moves to segregate even followed by odd elements in Array using Java programming language. The function will put all even numbers first, and then odd numbers and finally count the number of moves required to arrange all elements in the desired order.

Prerequisite

Knowledge of Java

Let’s move on to the example implementation…

Suppose we have an array of elements as 13, 10, 21, 20. Now we need to find out minimum to¬†segregate even followed by odd elements in Array so that all even elements will be in the front of the array and all odd elements will be in the back of the array. So the resulting array will 20, 10, 21, 13. It’s simply we need to swap element 13 with element 20 in the array. So we need only one move to segregate the even and odd elements in the array.

Source code

public class EvenOddArrayElements {

	public static void main(String[] args) {
		int[] arr = new int[] { 13, 10, 21, 20 };
		int minMoves = minMovesToEvenFollowedByOdd(arr);
		System.out.println("Minimum moves to segregate even followed by odd elements: " + minMoves);
	}

	static int minMovesToEvenFollowedByOdd(int[] arr) {
		int moves = 0;
		int totalLength = arr.length;
		for (int i = 0; i < totalLength / 2; i++) {
			if (arr[i] % 2 != 0) {
				for (int j = totalLength / 2; j < totalLength; j++) {
					if (arr[j] % 2 == 0) {
						int temp = arr[i];
						arr[i] = arr[j];
						arr[j] = temp;
						moves++;
						break;
					} else {
						continue;
					}
				}
			} else {
				continue;
			}
		}
		return moves;
	}
}

Testing the application

Now run the above code, you should see below output

Minimum moves to segregate even followed by odd elements: 1

Thanks for reading.

Minimum moves to segregate even followed by odd elements in Array
I am a professional Web developer, Enterprise Application developer, Software Engineer and Blogger and writing blogs is my passion. Connect me on Roy Tutorials | Twitter | Facebook | Linkedin | Reddit | Ello | Tumblr

Leave a Reply

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

Scroll to top