简体   繁体   English

插入排序 - 为什么代码对某些值集正确运行,而对其他集抛出 Array Index Out of Bounds Exception

[英]Insertion Sort - Why does the code run correctly for certain sets of values while throws Array Index Out of Bounds Exception for other sets

The code works perfectly fine when first input is the smallest value in the array whereas, for all other cases, the code throws ArrayIndexOutOfBoundsException -1当第一个输入是数组中的最小值时,代码可以正常工作,而对于所有其他情况,代码会抛出 ArrayIndexOutOfBoundsException -1

Test Input1: 6,8,7,11,9 (Works for this input)测试输入 1:6、8、7、11、9(适用于此输入)

Test Input2: 10,9,7,12,1 (Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: -1)测试输入 2:10,9,7,12,1(线程“主”java.lang.ArrayIndexOutOfBoundsException 中的异常:-1)

Please share what could be the reason for this and how to resolve this issue.请分享可能是什么原因以及如何解决此问题。

//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;
    }
}

You need to have the condition in your while loop like this: while (j >= 1 && data[j - 1] > key) {... } ie j >= 1 should be checked first and only if this is satisfied, data[j-1] > key should be checked.你需要在你的 while 循环中有这样的条件: while (j >= 1 && data[j - 1] > key) {... } ie j >= 1应该首先检查,并且只有在满足的情况下, data[j-1] > key应该被检查。

This is because first it should be checked that the index I'm going to access from the data is valid and then access it, otherwise IndexOutOfBoundException will occur.这是因为首先应该检查我要从data中访问的索引是否有效,然后再访问它,否则会发生IndexOutOfBoundException

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM