Wednesday, 28 August 2013

Segregate Even And Odd Numbers in given array

Given an array A[], write a function that segregates even and odd numbers. The functions should put all even numbers first, and then odd numbers.

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

  In the output, order of numbers can be changed, i.e., in the above example 34 can come before 12 and 3 can come before 9.

Algorithm 
segregateEvenOdd(int []array)
     1) Initialize two index variables left and right:
            left = 0,  right = size -1
     2) Increment left index until we see an odd number.
     3) Decrement right index until we see an even number.
     4) If left < right then swap arr[left] and arr[right].

Implementation

class SegregateEvenAndOddNumbers{
 
    static void segregate(int []a){
        if(a == null || a.length == 0)
            return;
        
        int left = 0, right = a.length - 1;
        while(left < right){
            
            while(a[left]%2 == 0 && left < right)
                left++;
            
            while(a[right]%2 != 0 && left < right)
                right--;
            
            if(left < right){
                swap(a, left, right);
                left++;
                right--;
            }
        }
    }
   
     //Utility function to swap array elements
    static void swap(int []a, int i, int j){
        int t = a[i];
        a[i] = a[j];
        a[j] = t;
    }
 
    public static void main(String []ar){
        int []a = {12, 34, 45, 9, 8, 90, 3};
        segregate(a);
        System.out.println("\nafter the shuffling" + java.util.Arrays.toString(a));
    }
}

1 comment:

  1. import java.util.ArrayList;


    public class Sample {
    public static void main(String[] args) {
    int[] input = {2,32,4235,4,5646,34,324,3,237,3245,324,324,2};
    input = segregate(input);
    for(int i: input){
    System.out.println(i);
    }
    }

    private static int[] segregate(int[] input) {
    //

    ArrayList odd = new ArrayList();
    ArrayList even = new ArrayList();

    for(int i: input){
    if(i%2 == 0){
    even.add(i);
    }
    else{
    odd.add(i);
    }
    }

    int count = 0;
    for(Integer i: odd){
    input[count] = i;
    count++;
    }
    for(Integer i: even){
    input[count] = i;
    count++;
    }

    return input;
    }
    }

    Time Complexity: O(N)

    ReplyDelete