Separate odd and even numbers in an array

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[])
 {
  
  for (int i = 0; i < arr.length; i++) {
   int left=0;
   int right=arr.length-1;
   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 

Written by Arpit:

If you have read the post and liked it. Please connect with me on Facebook | Twitter | Google Plus

 

Java tutorial for beginners Copyright © 2012