0

挿入ソートアルゴリズムのステップを印刷しようとしています

以前にC ++で書いて、とてもうまくいきましたが、に変換するJavaと、このエラーが発生しました

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: -1
at insertion.insertion_sort(insertionSort.java:45)
at insertionSort.main(insertionSort.java:8)

これは私のコードです:

    /* print the steps of insertion sort algorithm */

class insertionSort {

    public static void main(String[] args) {

        insertion obj = new insertion();
        obj.insertion_sort();

    } // end of main function

} // end of insertionSort class

class insertion {

    int A[] = { 5, 8, 9, 1, 0, 4, 7, 3, 6, 2 };
    final int ELEMENTS = 10;

    void printStep(int source, String destination) {
        System.out.print("move array[" + source + "]  -----> " + destination);
    }

    void printStep(int source, int destination) {
        System.out.print("move array[" + source + "]  -----> " + "array["
                + destination + "] ");
    }

    void printStep(String source, int destination) {
        System.out.print("move " + source + " -----> array[" + destination
                + "] ");
    }

    void insertion_sort() {

        int key, i;

        for (int j = 1; j < ELEMENTS; j++) {
            key = A[j];
            printStep(j, "key");
            System.out.println();
            i = j - 1;

            while (A[i] > key && i >= 0) {
                A[i + 1] = A[i];
                printStep(i + 1, i);
                System.out.println();
                i = i - 1;
            }

            A[i + 1] = key;
            printStep("key", i + 1);
            System.out.println();
            System.out.println("======================================");

        }

    } // end of insertion_sort ( )

} // end of insertion class

誰かが私の間違っているところを説明してください。

4

1 に答える 1

4

問題は while 検証にあります

while(A[i] > key && i >= 0)

i前に値を確認する必要がありますA[i]

while(i >= 0 && A[i] > key)

詳細な説明: このループ内で、変数whileの値を差し引いていることに注意してください。したがって、 が 0 未満になるi時があり、 をチェックする前にチェックしています。および文の検証の順序は重要です。Java はそれらを左から右に評価します。iA[-1]i >=0whileif

より詳しい情報:

于 2012-12-08T15:49:19.220 に答える