Question

This is an Interview question.

Say you have an array like this

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

How to sort it and classify as even or odd in a single line of code?

The answer's order of complexity should be O(1), without using any for loop. The result should be:

{2,4,54,1,5,23,23,65,545}
Was it helpful?

Solution

If instantiating and using an anonymous implementation of Comparator can be considered a single 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); }});

Ideone demo.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top