Java 插入排序-计数反转数

Java 插入排序-计数反转数,java,arrays,insertion-sort,Java,Arrays,Insertion Sort,我试图计算给定数据集的反转数。它对小数据集很有效,但一旦我从几千个数据集中选择一个,反转值就会变成负值。我看不出这是怎么可能的,有人知道为什么会发生这种情况/可能的修复吗 例如,如果数据集为5(-6,1,15,8,10),则反转值为2。然而,对于更长的数据集,我得到了-2032112517的反演 public static void main(String[] args) { Scanner userInput = new Scanner(System.in);

我试图计算给定数据集的反转数。它对小数据集很有效,但一旦我从几千个数据集中选择一个,反转值就会变成负值。我看不出这是怎么可能的,有人知道为什么会发生这种情况/可能的修复吗

例如,如果数据集为5(-6,1,15,8,10),则反转值为2。然而,对于更长的数据集,我得到了-2032112517的反演

    public static void main(String[] args) {
        Scanner userInput = new Scanner(System.in);
        System.out.println("Enter length of array: ");
        int input= userInput.nextInt();
        int[] values = new int[input];
        for (int i = 0; i < values.length; i++)
        {
            values[i] = userInput.nextInt();
        }
        insertionSort(values);

    }
    public static void insertionSort(int values[ ]) {
        int arrlen = values.length;
        int invert = 0;
        for (int i = 0; i < arrlen; i++) {
            int currentValue = values[i];
            int compare = i - 1;
            while (compare >= 0 && values[compare] > currentValue) {
                invert++;
                values[compare + 1] = values[compare];
                compare = compare - 1;
            }
            values[compare + 1] = currentValue;

        }
        System.out.println("INVERT IS: " +invert);

    }
publicstaticvoidmain(字符串[]args){
扫描仪用户输入=新扫描仪(System.in);
System.out.println(“输入数组长度:”);
int input=userInput.nextInt();
int[]值=新的int[输入];
对于(int i=0;i=0&&values[compare]>currentValue){
倒置++;
值[比较+1]=值[比较];
比较=比较-1;
}
值[比较+1]=当前值;
}
System.out.println(“反转为:“+INVERT”);
}

}Java中的最大int值为2147483647,很可能发生了溢出。试着用long代替

如果您想了解更多信息,请在Wikipedia上搜索整数溢出