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:
1 2 3 4 5 |
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 :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 |
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; } } |
1 2 3 4 5 6 |
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 |
Was this post helpful?
Let us know if this post was helpful. Feedbacks are monitored on daily basis. Please do provide feedback as that\'s the only way to improve.
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++;
}
}