首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

Java 插入排序錯誤分析:陣列索引越界與邏輯缺陷修正

     編輯:程式設計綜合問答

原始碼嘗試實作插入排序,但存在多處嚴重問題:

  • 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) 內建快速排序。重點在於理解「將當前元素插入已排序區間」的邏輯,避免索引越界與迴圈條件錯誤。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved