Segregate even and odd numbers

Input  = {12, 34, 45, 9, 8, 90, 3}
Output = {12, 34, 8, 90, 45, 9, 3} 

Method1: O(n) time

Keep incrementing left till we have even number.
Keep incrementing right till we have odd number.
Swap left and right if left less than right.

Code:

import java.util.*;

public class Solution {

    
    public static void main(String[] args) {
       
        int[] a = {12, 34, 45, 9, 8, 90, 3};
        int n = a.length;
        int left = 0, right = n-1;
        
        while(left<right){
            while(a[left]%2 == 0 && left< right){
                left++;
            }
            while(a[right]%2 !=0 && left< right){
                right--;
            }
            if(left<right && left<right){
                int temp = a[left];
                a[left] = a[right];
                a[right] = temp;
            }
        }
        
        System.out.print(Arrays.toString(a));
        
    }
}

Output:
[12, 34, 90, 8, 9, 45, 3]


Method2: O(n) time

In this method we will collect all even numbers in the left of the array.

Code:

import java.util.*;

public class Solution {

    
    public static void main(String[] args) {
       
        int[] a = {12, 34, 45, 9, 8, 90, 3};
        int n = a.length;
        int j = -1;
        
        for(int i=0; i<n; i++){
            if(a[i]%2 ==0 && j<i){
                j++;
                int temp = a[j];
                a[j] = a[i];
                a[i] = temp;
            }
        }

        System.out.print(Arrays.toString(a));
        
    }
}

Output:

[12, 34, 8, 90, 45, 9, 3]


Comments

Popular posts from this blog

Rearrange Array in Maximum-Minimum form

Find zeroes to be flipped so that number of consecutive 1's is maximized

Count substrings with same first and last character