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:

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 :

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

Was this post helpful?

Comments

  1. Thanks. Very helpful but how can we merge two unsorted arrays and also find smaller number of that unsorted array

  2. 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++;
    }

    }

Leave a Reply

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