## Wednesday, May 4, 2022

### Question 21 : Separate odd and even numbers in an array

Given an array of integers, you need to segregate odd and even numbers in an array.

Please note: Order of elements can be changed.

For example:
``````arr[] = {12, 17, 70, 15, 22, 65, 21, 90}
Array after separating odd and even numbers :
{12, 90, 70, 22, 15, 65, 21, 17}``````
• #### Algorithm

• Let's say array is arr[]
• Initialise two index variable , left=0 and right=arr.length-1
• Increment left variable until you get odd number
• Decrement right variable until you get even number.
• If left < right, swap arr[left] and arr[right]
• In the end, you will see that you have even numbers on left side and odd numbers on right side.

### Java code to separate odd and even numbers in an array

``````public class SeparateOddEvenMain {

public static void main(String[] args) {

int arr[] = {
12,
17,
70,
15,
22,
65,
21,
90
};

System.out.println("Original Array: ");
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}

arr = separateEvenOddNumbers(arr);
System.out.println("nArray after separating even and odd numbers : ");
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}

}

public static int[] separateEvenOddNumbers(int arr[]) {
int left = 0;
int right = arr.length - 1;

for (int i = 0; i < arr.length; i++) {

while (arr[left] % 2 == 0) {
left++;
}
while (arr[right] % 2 == 1) {
right--;
}

if (left < right) {
int temp = arr[left];
arr[left] = arr[right];
arr[right] = temp;
}
}

return arr;
}
}``````

when you run the above program, you will get the below output:

``````Original Array:
12 17 70 15 22 65 21 90
Array after separating even and odd numbers :
12 90 70 22 15 65 21 17``````