Sort all even numbers in ascending order and then sort all odd numbers in descending order

Prince Pereira
Jul 12, 2021
Input  : 1, 2, 3, 4, 5, 6, 7, 8
Output : 7, 5, 3, 1, 2, 4, 6, 8

Use comparator and sort. While sorting implement the compare method in such way that multiply -1 with odd numbers and compare, so that odd numbers will come in descending order.

Program

import java.util.*;public class OddEven {  public static void main(String[] args){
Integer[] arr = new Integer[]{1,2,3,4,5,6,7,8};
List<Integer> al = Arrays.asList(arr);
Collections.sort(al, new IntComparator());
System.out.println(al);
}
}
class IntComparator implements Comparator<Integer> {
public int compare(Integer o1, Integer o2){
int t1 = o1, t2 = o2;
if (t1%2 == 1) {
t1 = t1 * -1;
}
if (t2%2 == 1){
t2 = t2 * -1;
}
return t1 - t2;
}
}

--

--

Prince Pereira

Senior Software Engineer - Microsoft | SDN | Java | Golang | DS & Algo | Microservices | Kubernetes | Docker | gRPC & Protocol Buffer