首页 > 解决方案 > 插入排序 - 为什么代码对某些值集正确运行,而对其他集抛出 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;
    }
}

标签: javasortingdata-structuresinsertion-sort

解决方案


你需要在你的while循环中有这样的条件:while (j >= 1 && data[j - 1] > key) { ... }j >= 1应该首先检查,只有当它满足时,才data[j-1] > key应该检查。

这是因为首先应该检查我要访问的索引data是否有效,然后访问它,否则IndexOutOfBoundException会发生。


推荐阅读