Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Part1Basic/JAVA/src/main/java/Chapter2SortingBasic/Section6InsertionSortOptimize/InsertionSort.java,发现一个bug #1

Open
naruto227 opened this issue Sep 16, 2020 · 2 comments

Comments

@naruto227
Copy link

naruto227 commented Sep 16, 2020

public static void sort(Comparable[] arr) {
        int n = arr.length;
        // 注意下标从1开始,不停往前比较,下标为0的元素默认有效
        for (int i = 1; i < n; ++i) {
            // 先把起始位置的元素暂存
            Comparable tmp = arr[i];
            // 从位置i开始,从前挨个比较(前面已经是有序地了,这个是前提),一直比较到前面的某个元素比自己小就停下
            for (int j = i; j > 0; j--) {
                if (tmp.compareTo(arr[j - 1]) < 0) {
                    // 起始位置元素比前面的小,就把前面的值附到后面来元素上
                    arr[j] = arr[j - 1];
                } else {
                    // 一直到j前面的元素j-1小于tmp了,说明升序排列完成,把之前存的起始位置元素tmp插入到此处即可
                    arr[j] = tmp;
                    break;
                }
            }

        }

当j=0时,不会进入for循环。arr[j] = tmp;应该写在内部循环的外面。

public static void sort(Comparable[] arr) {
        int n = arr.length;
        // 注意下标从1开始,不停往前比较,下标为0的元素默认有效
        for (int i = 1; i < n; ++i) {
            // 先把起始位置的元素暂存
            Comparable tmp = arr[i];
            int j = i;
            // 从位置i开始,从前挨个比较(前面已经是有序地了,这个是前提),一直比较到前面的某个元素比自己小就停下
            for (; j > 0; j--) {
                if (tmp.compareTo(arr[j - 1]) < 0) {
                    // 起始位置元素比前面的小,就把前面的值附到后面来元素上
                    arr[j] = arr[j - 1];
                } else {
                    // 一直到j前面的元素j-1小于tmp了,说明升序排列完成,把之前存的起始位置元素tmp插入到此处即可
                    break;
                }
            }
            arr[j] = tmp;

        }
    }
@lsgwr
Copy link
Owner

lsgwr commented Sep 16, 2020

我看了下,j的初始值是i,i的取值范围是1~n,j取不到0地

@naruto227
Copy link
Author

我看了下,j的初始值是i,i的取值范围是1~n,j取不到0地

举个例子:8 5 4 5 0 9,执行第一次循环,j = 1,结果:8 8 4 5 0 9;执行j--后,j = 0;不会进入内循环了,arr[j] = tmp;就没有执行了

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants