【发布时间】:2020-10-02 06:36:06
【问题描述】:
这是 Java 中插入排序的简单代码。我尝试减少 Java 代码的行数。但这不能解决这个问题。我想知道为什么做不到。
我尝试过的代码(错误发生在第 9 行)
import java.util.Scanner;
public class InsertionSortModified {
public static int[] insertionSort(int[] arr) {
for (int i = 1; i < arr.length; i++) {
int temp = arr[i];
int pos = i;
while (pos > 0 && arr[pos-1] > temp)
arr[pos--] = arr[pos-1];
arr[pos] = temp;
}
return arr;
}
public static void main(String args[]) {
Scanner scnr = new Scanner(System.in);
int elementarr[] = new int[5];
for (int j = 0; j < 5; j++)
elementarr[j] = scnr.nextInt();
elementarr = insertionSort(elementarr);
for (int j = 0; j < elementarr.length; j++)
System.out.print(elementarr[j] + " ");
}
}
命令窗口中显示错误
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: -1
at InsertionSortModified.insertionSort(InsertionSortModified.java:9)
at InsertionSortModified.main(InsertionSortModified.java:22)
当代码修改为这样时,程序正在运行。 (第 8 到 11 行)
while (pos > 0 && arr[pos-1] > temp) {
arr[pos] = arr[pos-1];
pos--;
}
为什么我不能使用
arr[pos--] = arr[pos-1];
【问题讨论】:
-
您遇到了哪个错误?请添加完整的堆栈跟踪。
-
我已经编辑了错误的问题。
-
Postdecrement 表示在获取值后递减,而不是在执行一行后递减,所以
arr[pos--] = arr[pos];将是你的单行
标签: java arrays algorithm data-structures insertion-sort