TimSort排序BUG

2024/3/10

# 💧源码

# 📜使用说明

# 异常信息

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 java.base/java.util.Arrays$ArrayList.sort(Arrays.java:4405)
	at sort.TestComparatorException.sort(TestComparatorException.java:47)
	at sort.TestComparatorException.main(TestComparatorException.java:38)

# 复现代码

public static void main(String[] args) {
        sort(0,1, 1, 1, 1, 1, 2, 1, 1, 1);
        sort(3, 2, 3, 2, 1, 31);
        sort(2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3);
        // exception
        // java version "1.8.0_40" "1.8.0_191" "1.8.0_212" "AdoptOpenJDK-11.0.10+9"
        // --------------------------------------
        // 数组长度大于等于64时才会使用TimSort算法
        // --------------------------------------
        sort(1, 2, 3, 2, 2, 3, 2, 3, 2, 2, 3, 2, 3, 3, 2, 2, 2, 2, 2, 2, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
            1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1);
    }

    private static void sort(Integer... ints) {
        List<Integer> list = Arrays.asList(ints);
        list.sort((o1, o2) -> {
            if (o1 < o2) {
                return -1;
            } else {
                return 1;
            }
        });
        System.out.println(list);
    }