Skip to content
Advertisement

Sort character array using java comparator

Sort a character array lexicographically with an additional condition that all c’s comes before all b’s. This could be done manually but I want to code it via inbuilt sorting using comparators. The code I wrote –

JavaScript

Gives output: [a, a, a, a, a, b, c, b, d, r, r]. The c only comes before one of the b’s. If I change the comparator to the following then it gives the correct output.

JavaScript

My question is why in both cases returning “y-x” gives the correct answer? If in one case returning “y-x” was correct then in the other case shouldn’t returning “x-y” would have been correct? Instead of “y-x”, returning a -1 or +1 doesn’t work either. Pl. explain what is happening internally. Thanks!

Advertisement

Answer

The problem is that if passing 'c' and 'b' makes the comparison return a negative value, then passing 'b' and 'c' should return a positive one (And your first version returns a negative number in that case instead). If the function doesn’t return consistent results no matter the order of arguments, the sort algorithm is going to produce a garbage order.

Consider this version:

JavaScript
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement