Home > Enterprise >  Segregate_even_odd_numbers
Segregate_even_odd_numbers

Time:10-04

given an array of integers, segregate even and odd numbers in the array. All the even numbers should be present first, and then the odd numbers.

Examples:

Input: arr[] = 1 9 5 3 2 6 7 11
Output: 2 6 5 3 1 9 7 11

Input: arr[] = 1 3 2 4 7 6 9 10
Output:  2 4 6 10 7 1 9 3

public class Segregate_even_odd_numbers {

    public static void main(String[] args) {  
        int a[]= { 1, 3, 2, 4, 7, 6, 9, 10 };
        int n=a.length;         
        int ind=0;
        
        for(int i=0;i<n;i  ){
            if(a[i]%2==0){
                a[ind]=a[i];
                ind  ;
            }
        }
        
        for(int i=0;i<n;i  ){
            if(a[i]%2!=0){
                a[ind]=a[i];
                ind  ;
            }
        }
        
        for(int i=0;i<n;i  ){
            System.out.println(a[i]   " ");
        }
        
        System.out.println("");
    }
}

I am getting output like this

2 
4 
6 
10 
7 
9 
9 
10 

0th index and 1st index not calculate.

what mistake I made, please guide me.

CodePudding user response:

You're program is almost correct, but needs little modification, below is the implementation and explanation

public class Segregate_even_odd_numbers {
public static void main(String[] args) {
    int a[] = { 1, 9, 5, 3, 2, 6, 7, 11 };
    int n = a.length;
    int evenIndex = 0;

    for (int i = 0; i < n; i  ) {
        if (a[i] % 2 == 0) {
            int temp = a[i];
            a[i] = a[evenIndex];
            a[evenIndex] = temp;
            evenIndex  ;

        }
    }

    for (int i = 0; i < n; i  ) {
        System.out.print(a[i]   " ");
    }

    System.out.println("");
} }

What are we doing here:

  1. We maintain a evenIndex pointer at 0 index
  2. Whenever we find any Even value we swap it with evenIndex i.e.., arr[evenIndex] = arr[i] and place arr[i] = arr[evenIndex]
  3. This code works does not modify any values if you pass an array with only Even Numbers or Odd Numbers

Time Complexity : O(n) Space Complexity : O(1)

CodePudding user response:

This can also be accomplished by sorting the array based on the value of each element modulo 2.

int[] a= { 1, 3, 2, 4, 7, 6, 9, 10 };
int[] res = Arrays.stream(a).boxed().sorted(Comparator.comparingInt(x -> x & 1))
               .mapToInt(i -> i).toArray();
System.out.println(Arrays.toString(res));
  • Related