插入排序 - 为什么代码 运行 对某些值集正确而对其他集抛出数组索引越界异常
Insertion Sort - Why does the code run correctly for certain sets of values while throws Array Index Out of Bounds Exception for other sets
当第一个输入是数组中的最小值时,代码工作得很好,而对于所有其他情况,代码会抛出 ArrayIndexOutOfBoundsException -1
测试输入 1:6,8,7,11,9(适用于此输入)
测试输入 2:10,9,7,12,1(线程“main”中的异常 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
。
当第一个输入是数组中的最小值时,代码工作得很好,而对于所有其他情况,代码会抛出 ArrayIndexOutOfBoundsException -1
测试输入 1:6,8,7,11,9(适用于此输入)
测试输入 2:10,9,7,12,1(线程“main”中的异常 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
。