Sort an even number and an odd number on one line

This is an interview question.

Let's say you have such an array

{54,23,545,65,23,4,1,2,5} 

How to sort and classify as odd or even in one line of code?

The complexity response order should be O (1), without using a for loop. The result should be:

 {2,4,54,1,5,23,23,65,545} 
+4
source share
1 answer

If creating and using an anonymous implementation of Comparator can be considered as one line:

 Arrays.sort(arr, new Comparator<Integer>(){public int compare(Integer o1, Integer o2) {return o1%2 == o2%2 ? o1.compareTo(o2) : (o1%2 == 0 ? -1 : 1); }}); 

The perfect demonstration .

+6
source

Source: https://habr.com/ru/post/1484628/


All Articles