0

How can I sort array according to the count of set bits? I'm getting an error whit below code:

Arrays.sort(arr, (o1, o2) -> {
    if (Integer.bitCount(o1) <=  Integer.bitCount(o2))
        return 1;
    return -1;
});

Exception:

Exception in thread "main" java.lang.IllegalArgumentException: Comparison method violates its general contract!
    at java.base/java.util.TimSort.mergeLo(TimSort.java:781)
    at java.base/java.util.TimSort.mergeAt(TimSort.java:518)
    at java.base/java.util.TimSort.mergeCollapse(TimSort.java:448)
    at java.base/java.util.TimSort.sort(TimSort.java:245)
    at java.base/java.util.Arrays.sort(Arrays.java:1441)
    at Compute.sortBySetBitCount(File.java:44)
    at GFG.main(File.java:23)

How to fix this?

Tolga Evcimen
  • 7,112
  • 11
  • 58
  • 91
  • 5
    You **have to** return 0 when objects are "equals". – Matthieu Jun 20 '21 at 15:40
  • 1
    Does this answer your question? [Java error: Comparison method violates its general contract](https://stackoverflow.com/questions/11441666/java-error-comparison-method-violates-its-general-contract). Tip: paste error messages you don’t understand immediately into your search engine. – Ole V.V. Jun 20 '21 at 17:18

1 Answers1

6

You never return 0, even if the elements are equal. Using the Comparator.comparing methods is generally better for simple sorting methods.

Arrays.sort(arr, Comparator.comparingInt(Integer::bitCount).reversed());
Unmitigated
  • 76,500
  • 11
  • 62
  • 80