[英]Whenever I run the insertion sort program in java, exception occurs .. but i don't know why
Below is my code for Insertion Sort and i am facing an exception of array indexing.下面是我的插入排序代码,我面临数组索引的异常。
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]);
}
}
}
This is the exception i am getting everytime i run this这是我每次运行时都会遇到的异常
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index -1 out of bounds for length 4
at dfsd.Insertion_Sort.main(Insertion_Sort.java:17)
First thing is that you should check j >= 0
first and if that happen check second condition which is ar[j] > ar[i]
.首先,您应该首先检查
j >= 0
,如果发生这种情况,请检查第二个条件,即ar[j] > ar[i]
。 but there is another problem ar
array is changing during the process and you should use c
instead of ar[i]
so the condition would be: j >= 0 && ar[j] > c
.但是在此过程中还有另一个问题
ar
数组正在发生变化,您应该使用c
而不是ar[i]
所以条件是: j >= 0 && ar[j] > c
。 Here is the working version of your code:这是您的代码的工作版本:
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 (j >= 0 && ar[j] > c) {
ar[j + 1] = ar[j];
j--;
}
ar[j + 1] = c;
}
for (int i = 0; i < n; i++) {
System.out.println(ar[i]);
}
}
J>=0 should be the first condition. J>=0 应该是第一个条件。 Also you need to check j<n as you are using j+1 in the check (scenario when i reached n-1) to avoid exceptions.
此外,您需要检查 j<n,因为您在检查中使用 j+1(当我达到 n-1 时的场景)以避免异常。 The logic of insertion sort seems to be incorrect.
插入排序的逻辑似乎是不正确的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.