java - 插入排序 - 计算反转次数
问题描述
我正在尝试计算给定数据集的反转次数。它适用于小型数据集,但是一旦我选择了几千个中的一个,反转值就会变成负数。我看不出这是怎么可能的,有谁知道为什么会发生这种情况/可能的修复?
例如,给定一个 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);
}
}
解决方案
Java 中的最大 int 值为 2147483647,很可能发生了溢出。尝试使用 long 代替。
如果您想了解更多信息,请在 Wikipedia 上搜索 Integer overflow。
推荐阅读
- javascript - Ajax 调用以获取从 HTML 选择选项中选择的值
- reactjs - 以 redux 形式设置 initValues
- javascript - Mapbox 3D 线解决方法
- php - 如何使用 PHP 读取发送到我的服务器 IP 地址和特定端口的数据?
- c# - .NET Core 添加/构建 .cs 文件到目标项目
- c# - 如何标记关闭的应用程序是否从使用 MvvmCross 和自定义应用程序启动的推送通知启动
- java - 在文本末尾显示“阅读更多”无法正常工作
- node.js - 使用 TypeScript 和 Node/Passport 将异步回调传递给类构造函数
- php - 我已经填写了每个字段,但仍然在 laravel 的用户表中显示 SQLSTATE[HY000] 为什么?
- sql-server - 使用 powershell 创建 SQL 脚本传输失败