首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >插入排序代码错误

插入排序代码错误
EN

Stack Overflow用户
提问于 2012-12-08 23:44:49
回答 1查看 248关注 0票数 0

我正在尝试打印插入排序算法的步骤

我以前是用c++写的&它工作得很好,但是当我转换成Java时,它给了我这个错误

代码语言:javascript
复制
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: -1
at insertion.insertion_sort(insertionSort.java:45)
at insertionSort.main(insertionSort.java:8)

这是我的代码:

代码语言:javascript
复制
    /* 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

请谁来解释一下我哪里错了?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2012-12-08 23:49:19

问题出在您的while验证中。

代码语言:javascript
复制
while(A[i] > key && i >= 0)

必须在A[i]之前检查i

代码语言:javascript
复制
while(i >= 0 && A[i] > key)

进一步的解释:请注意,在这个while循环中,您将扣除i变量的值。所以会有一段时间,当i小于0的时候,在检查i >=0之前先检查A[-1]whileif语句中验证的顺序很重要,Java会从左到右对它们进行评估。

更多信息:

票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/13779011

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档