Site icon

Classify or segregate array containing even & odd numbers in java (example)

Fig 1: Input Array

Algorithm to classify even & odd numbers in an array using java

  1. Take two indexes low and high [Shown in Fig 2].
    • low index points lowest position of array (low = 0).
    • high index points to highest position of array (high = array’s length – 1).
  2. Increments low index till, we find odd number.
    • Stop, when we found out odd number.
  3. Decrements high index till, we find even number.
    • Stop, when we found out even number.
  4. Now swap the values pointed by low and high index (odd number and even number).
    • After swapping, even number will come in left side of array and odd number will be come in right side of array.
  5. After performing the above algorithm, whole array will be classified into even and odd numbers.

Step 1:  

Fig 2: Initialize low and high variables

Step 2:

Fig 3: Swap Even and odd number

Step 3:

Fig 4: Array after swapping even and odd number

Step 4:

Fig 5: Final Segregated array

Time complexity of algorithm is O (n).

Program – segregate array containing even & odd numbers in java

import java.util.Arrays;

public class SegregateEvenAndOdd {
	public static void main(String[] args) {
		int[] arr = { 10, 11, 20, 31, 50, 61, 90 };
		segregateArray(arr);
		System.out.println("Segregated array is : "+Arrays.toString(arr));
		
	}
	private static void segregateArray(int[] arr) {
		
		int low = 0;
		int high = arr.length - 1;
		
		while(low < high) {
			//increment till we find 1
			while(arr[low]%2 == 0 && low < high)
				low ++;
			
			//decrement till we find 0
			while(arr[high]%2 != 0 && low < high)
				high--;
			
			if(low < high) {
				//Swap 
				int temp = arr[low];
				arr[low] = arr[high];
				arr[high] = temp;
				low ++;
				high--;
			}
		}
		return;
	}
}

Output- classify even & odd numbers in array

Segregated array is : [10, 90, 20, 50, 31, 61, 11]
Exit mobile version