【发布时间】:2021-05-24 02:20:15
【问题描述】:
以下是我的插入排序代码,我正面临数组索引异常。
import java.util.Scanner;
public class Insertion_Sort {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int n=4;
int ar[]=new int[n];
for(int i=0;i<n;i++)
{
ar[i]=sc.nextInt();
}
for(int i=1;i<n;i++)
{
int c=ar[i];
int j=i-1;
while(ar[j]>ar[j+1] && j>=0)
{
ar[j+1]=ar[j];
j--;
}
ar[j+1]=c;
}
for(int i=0;i<n;i++)
{
System.out.println(ar[i]);
}
}
}
这是我每次运行时都会遇到的异常
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index -1 out of bounds for length 4
at dfsd.Insertion_Sort.main(Insertion_Sort.java:17)
【问题讨论】:
-
错误告诉你究竟出了什么问题。如何访问数组的位置 -1?
-
具体来说,您能想到
while(ar[j]>ar[j+1] && j>=0)可能会导致问题的时间吗?j>=0将不会首先被检查。 -
第 17 行是哪一行?请不要隐藏调试所需的信息。
-
@Swapnil 错误的原因是你必须使用
while (j >= 0 && ar[j] > ar[j+1])。这是必要的。在这里查看更多信息:stackoverflow.com/questions/8759868/… -
@Swapnil 您还对
insertion sort使用了不正确的逻辑。在while循环中进行必要的更改后,结果输出将是错误的。改正吧。
标签: java sorting insertion-sort