原始碼嘗試實作插入排序,但存在多處嚴重問題:
for(int i=1; in[0]; j--) 語法錯誤,in 未定義且條件判斷錯誤。n[j+1]=n[j]; n[j]=n[0]; 在 j 為陣列最後一格時會導致 j+1 索引越界。System.exit(0)。public static void insertionSort(int[] a) {
for (int i = 1; i < a.length; i++) {
int key = a[i];
int j = i - 1;
while (j >= 0 && a[j] > key) {
a[j + 1] = a[j];
j--;
}
a[j + 1] = key;
}
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int[] scores = new int[5];
for (int i = 0; i < scores.length; i++) scores[i] = sc.nextInt();
insertionSort(scores);
for (int v : scores) System.out.print(v + "\t");
}
或直接使用 Arrays.sort(scores) 內建快速排序。重點在於理解「將當前元素插入已排序區間」的邏輯,避免索引越界與迴圈條件錯誤。