# Minimum moves to segregate even followed by odd elements in Array

## Introduction

This tutorial will find out minimum moves to segregate even followed by odd elements in an 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. This example does not consider any duplicate element in the array.

## Prerequisite

Knowledge of Java

## Example

Let’s move on to the example implementation…

Suppose you have an array of elements as `13, 10, 21, 20`.

Now you need to find out minimum moves to segregate even followed by odd elements in the 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 you need to swap element `13` with element `20` in the array. So you need only one move to segregate the even and odd elements in the array.

## Source Code

The complete source code in Java is given below:

``````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``

That’s all about moving elements to segregate even followed by odd elements in an array.

## One Thought to “Minimum moves to segregate even followed by odd elements in Array”

1. Ania

need to modify the program in case of duplicates
example-
5
8
5
11
4
6