javasortingcomparator

Sorting a list based on custom comparator while not changing the place of negative numbers


Sorting a list of integers except negative numbers in java , negative numbers indexes should remain same I tried to achieve above condition using a custom comparator but it fails

list.sort((a,b)->(a<0||b<0)?0:a-b);

Input list -
40,20,-2,0,-5,25,-3,44,24,29,38
Output list -
0,20,25,40,-2,-5,-3,24,29,38,44
Output expected -
0,20,-2,24,-5,25,-3,29,38,40,44

What's wrong with above comparator based approach? Can this problem be resolved using comparator?


Solution

  • Good instinct in trying to solve your problem using existing libraries instead of re-inventing the wheel^^.

    In your case, regrettably, you need to allocate a new List of the elements you actually want to sort before you can use List.sort.

    Where you can read up: While you formally defined a "Comparator", you did not fulfil the contract a java Comparator is always expected to fulfil. What you must implement is the compare function, which has to "ensure that compare(x, y)==0 implies that signum(compare(x, z))==signum(compare(y, z)) for all z.". Yours does not do this: signum(compare(1, -1) = 0, but signum(compare(1,2))!=signum(compare(-1,2).

    What you need to understand: What you give the List.sort() as an argument, is not an instruction on how to react when it decides if to reorder two elements or not, you give it a description of the desired output, which has to be a total ordering. When you tell List.sort (a,b)->1, this means "in the desired output I want to see all occurences of b before all occurences of a". You can't describe your desired output in such a way, it just is no total ordering of Integers, so can't be expressed by a Comparator.