![](/img/trans.png)
[英]Whenever I am calling “InsertionSort” method the output file is appearing empty? Where should I call this method?
[英]Why i am not able to get output in Insertionsort Coded java
我在实现InsertionSort时无法获得输出
package app;
public class InsertionSortDemo {
public static void insertionsort1(int A[]) {
int i,j,v;
for(i=2;i<=A.length-1;i++) {
v=A[i];
j=i;
while(A[j-1]>v && j>=1) {
A[j]=A[j-1];
j--;
}
A[j]=v;
}
}
public static void main(String s[]) {
int ar[]={6,8,1,4,5,3,7,2};
insertionsort1(ar);
}
}
显示的输出:
线程“主”中的异常java.lang.ArrayIndexOutOfBoundsException:-1
在app.InsertionSortDemo.insertionsort1(InsertionSortDemo.java:11)
在app.InsertionSortDemo.main(InsertionSortDemo.java:23)
问题在这里:
while(A[j-1]>v && j>=1)
Java中的条件从左到右评估。 因此,当j
的值为0
,您将访问A[-1]
,从而导致异常。
只需更改您验证while
循环的方式即可:
while(j>=1 && A[j-1]>v)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.