java - 插入排序 - 为什么代码对某些值集正确运行,而对其他集抛出 Array Index Out of Bounds Exception
问题描述
当第一个输入是数组中的最小值时,代码可以正常工作,而对于所有其他情况,代码会抛出 ArrayIndexOutOfBoundsException -1
测试输入 1:6、8、7、11、9(适用于此输入)
测试输入 2:10,9,7,12,1(线程“主”java.lang.ArrayIndexOutOfBoundsException 中的异常:-1)
请分享可能是什么原因以及如何解决此问题。
//SortingMain.java
import java.util.Scanner;
public class SortingMain {
public static void main(String[] args) {
int data[] = new int[5];
Scanner input = new Scanner(System.in);
InsertionSort obj = new InsertionSort();
System.out.println("Enter the numbers in array:");
for(int i=0; i<5;i++) {
data[i]=input.nextInt();
}
obj.insertionSort(data);
System.out.println("Elements after sorting");
for(int i=0; i<5;i++) {
System.out.println(data[i] + " ,");
}
input.close();
}
}
//InsertionSort.java
public class InsertionSort {
public void insertionSort(int data[]) {
int i,j,key;
for(i=1;i<data.length;i++) {
key=data[i];
j=i;
while(data[j-1]>key && j>=1) {
data[j] = data[j-1];
j--;
}
data[j] = key;
}
}
解决方案
你需要在你的while循环中有这样的条件:while (j >= 1 && data[j - 1] > key) { ... }
即j >= 1
应该首先检查,只有当它满足时,才data[j-1] > key
应该检查。
这是因为首先应该检查我要访问的索引data
是否有效,然后访问它,否则IndexOutOfBoundException
会发生。
推荐阅读
- c# - System.FormatException: 'Index (zero based) must be greater than or equal to zero and less than the size of the argument list
- vuejs2 - 无法从 vue 组件访问另一个类
- c++ - 是否可以为模板类的模板函数成员起别名?
- c# - 如何从 datagridview 中设置选定的单元格值并使用它插入数据库?
- c# - ASP NET MVC 5:会话突然结束
- node.js - 是否可以使用代理网址提供视频内容?
- laravel - 动态子域 Laravel
- java - 在 Play (Java) 中实现 OAuth2 的密码所有者资源流程
- java - Spring Boot 和 Docker-compose 设置参数
- azure-cognitive-search - Azure 搜索:Orderby 如何处理空整数值?