java - 我正在执行插入排序并在我的 while 循环中获取数组越界异常

标签 java algorithm sorting

插入排序

import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
class solution {
    public static void main(String[] args)
    {
        Scanner scan = new Scanner(System.in);
        int n = scan.nextInt();
        int[] a = new int[n];
        for (int i=0; i<n; i++)
        {
            a[i]=scan.nextInt();
        }
        for (int i=0; i<n; i++)
        {
            /*storing current element whose left side is checked for its
             correct position .*/
            int temp = a[i];
            int j=i;
            /* check whether the adjacent element in left side is greater or
            less than the current element. */
            while ((temp<a[j-1]) && (j>=0))
            {
                // moving the left side element to one position forward.
                a[j] = a[j-1];
                j = j-1;
                // moving current element to its  correct position.
                a[j] = temp;
            }
        }
        System.out.println("Sorted elements are:");
        for(int i=0;i<n;i++)
        {
            System.out.println(a[i]);
        }
    }
}

我不明白为什么我的代码会抛出这个异常:

thread "main" java.lang.ArrayIndexOutOfBoundsException: -1 at solution.main(insertion.java:24)

在我的 while 循环中。请指导我解决这个异常。

最佳答案

for(int i=0;i<n;i++)

我从0开始,所以第一次

i=0
j=i

再次 a[j-1] 将是 a[(0 - 1)] = a[-1]这里

 while((temp<a[j-1]) && (j>=0)) // array index starts from 0

因此异常(exception)

应该是这样

while((j>0) && (temp<a[j-1]) )

这是short-circuit(&&)运算符的特性,只有前一个表达式为真时才会计算下一个表达式。

关于java - 我正在执行插入排序并在我的 while 循环中获取数组越界异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39888420/

相关文章:

javascript - ESC POS 蓝牙打印机清除缓冲区

java - 我正在尝试检查电子邮件是否具有三个字母的扩展名,例如 ".com"或 ".net",但这不起作用

java - 解释暴力算法

在图像中找到正方形的算法?

在 Lua Redis 中使用下划线排序

java - 如果在代理模式中,我们在代理类中有接口(interface)而不是实际的具体主题,它是否等同于装饰器模式

java - 通过 Google Cloud Datastore 进行地理空间查询

php - 对多维关联数组进行排序?

oracle - pl sql 尝试创建字符串算法

在hadoop中对输出文本文件进行排序,有没有办法不排序就可以查看输出?或使用不同的排序方法?