Saturday, January 30, 2016

Even odd numbers sort

Problem:
Given n random numbers. Move all even numbers on left hand side and odd numbers on right hand side and then sort the even numbers in increasing order and odd numbers in decreasing order
For example, i/p : 3 6 9 2 4 10 34 21 5
o/p: 2 4 6 10 34 3 5 9 21
Solution:
Solution:
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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
package Arrays;
 
import java.util.Arrays;
import java.util.Collections;
 
public class EvenOddSort {
         
    public Integer[] evenOddSort(Integer[] a){
        int i, j;
        i=0; j = a.length-1;
        // move even numbers in first half and odd numbers in secound half
        while(i < j ){
            // even number then go further
            if(a[i]%2 == 0){
                i++;
            }
            // odd number then go further
            else if(a[j]%2 == 1) {
                j--;
            }
            else if(a[i]%2 == 1 && a[j]%2 == 0){
                swap(a, i, j);
                i++;
                j--;
            }          
        }
        // keep the boundary of even and odd indexes correctly
        if(a[i]%2 == 0) {
            i++;
        }      
         
        // sort even numbers in ascending order
        Arrays.sort(a, 0, i);
        // sort odd numbers in descending order
        Arrays.sort(a, i, a.length, Collections.reverseOrder());
         
        return a;
    }
     
    private void swap(Integer[] a, int i, int j){
        int temp = a[i];
        a[i]=a[j];
        a[j]=temp;
    }
     
    private void print(Integer[] a){
        System.out.println("Even Odd sorting");
        for(Integer i : a){
            System.out.print(i+" ");
        }
    }
     
    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
         
        EvenOddSort e = new EvenOddSort();
        Integer[] a = {3, 6, 9, 2, 4, 10, 34, 21, 5};
        //Integer[] a = {11, 10, 6, 9, 3, 1, 2, 33, 2, 5, 4, 4};
         
        //Integer[] a = {12, 67, 1, 34, 9, 78, 6, 31};
         
        e.print(e.evenOddSort(a));
 
    }
 
}

No comments:

Post a Comment