Problem :
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:
Lets 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 :
package org.arpit.java2blog;
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 above program, you will get 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
Thanks. Very helpful but how can we merge two unsorted arrays and also find smaller number of that unsorted array
Below is better approach :
while(low<=high){
if(arr[low]%2!=0){
if(arr[high]%2==0) {
int temp = arr[low];
arr[low] = arr[high];
arr[high] = temp;
low++;
high–;
}else{
high–;
}
}else{
low++;
}
}