gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-11-01 02:59:30 25 4
gpt4 key购买 nike

插入排序

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com