Sort all even numbers in ascending order and then sort all odd numbers in descending order in a collection
Any collection that supports sorting with a custom comparer will do - even an array. Implement your custom comparator as follows:
public int compare(int x, int y) {
if (x&1 == y&1) {
// Both numbers are odd or both numbers are even
if (x&1 == 0) {
// Both numbers are even: compare as usual
return Integer.compare(x, y);
} else {
// Both numbers are odd: compare in reverse
return Integer.compare(y, x);
}
}
// One is odd, the other one is even
if (x&1 == 0) {
return -1;
}
return 1;
}
You could do as follows
public ArrayList<Integer> sort(Integer[] input) {
int length = input.length;
ArrayList<Integer> oddNumber = new ArrayList<Integer>(0);
ArrayList<Integer> evenNumber = new ArrayList<Integer>(0);
for (int i = 0; i < length; i++) {
Integer val = input[i];
if(isEven(val)){
evenNumber.add(val);
} else {
oddNumber.add(val);
}
}
Collections.sort(evenNumber);
Collections.sort(oddNumber, Collections.reverseOrder());
evenNumber.addAll(oddNumber);
return evenNumber;
}
public boolean isEven(Integer x) {
return x % 2 == 0;
}
EDIT
I implemented a comparator based on Jesper algorithm.
public ArrayList<Integer> sort(Integer[] input) {
ArrayList<Integer> output = new ArrayList<Integer>(0);
output.addAll(Arrays.asList(input));
Collections.sort(output, new EvenOddComparator());
return output;
}
public class EvenOddComparator implements Comparator<Integer>
{
final int BEFORE = -1;
final int EQUAL = 0;
final int AFTER = 1;
@Override
public int compare(Integer o1, Integer o2) {
if (o1 % 2 == 0 && o2 % 2 != 0) {
return BEFORE;
} else if (o1 % 2 != 0 && o2 % 2 == 0) {
return AFTER;
} else if (o1 % 2 == 0 && o2 % 2 == 0) {
return o1.compareTo(o2);
} else if (o1 % 2 != 0 && o2 % 2 != 0) {
return o2.compareTo(o1);
}
return EQUAL;
}
}
Cheers.