'Comparator Error java.lang.IllegalArgumentException [closed]
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?
Solution 1:[1]
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());
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source | 
|---|---|
| Solution 1 | 
