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

shell排序算法写错了 #63

Closed
keqizwl opened this issue Mar 16, 2018 · 5 comments
Closed

shell排序算法写错了 #63

keqizwl opened this issue Mar 16, 2018 · 5 comments
Labels
invalid 不再有效

Comments

@keqizwl
Copy link

keqizwl commented Mar 16, 2018

第一层循环应该是0到h-1

@CyC2018
Copy link
Owner

CyC2018 commented Mar 16, 2018

@keqizwl 没有错的

@CyC2018
Copy link
Owner

CyC2018 commented Mar 16, 2018

@keqizwl

import java.util.Arrays;

public class Shell {
    public static void sort(Comparable[] a) {
        int N = a.length;
        int h = 1;
        while (h < N / 3) {
            h = 3 * h + 1; // 1, 4, 13, 40, ...
        }
        while (h >= 1) {
            for (int i = h; i < N; i++) {
                for (int j = i; j >= h && less(a[j], a[j - h]); j -= h) {
                    exch(a, j, j - h);
                }
            }
            h = h / 3;
        }
    }

    private static void exch(Comparable[] a, int i, int j) {
        Comparable t = a[i];
        a[i] = a[j];
        a[j] = t;
    }

    private static boolean less(Comparable x, Comparable y) {
        return x.compareTo(y) < 0;
    }

    public static void main(String[] args) {
        Integer[] a = {1, 3, 2, 4, 8, 7, 0};
        sort(a);
        System.out.println(Arrays.toString(a));
    }
}
[0, 1, 2, 3, 4, 7, 8]

@CyC2018 CyC2018 closed this as completed Mar 16, 2018
@keqizwl
Copy link
Author

keqizwl commented Mar 17, 2018

排序没错,因为当h为1的时候就是插入排序,肯定能排正确,但是算法不是正确的shell算法,你可以搜索下shell算法实现,对比下。

@CyC2018
Copy link
Owner

CyC2018 commented Mar 17, 2018

@keqizwl 麻烦给以下比较权威的资料,我找到的方法都是这么实现的。

@keqizwl
Copy link
Author

keqizwl commented Mar 17, 2018

不好意思,是我弄错了,你实现是对的

@CyC2018 CyC2018 added the invalid 不再有效 label Jul 22, 2018
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
invalid 不再有效
Projects
None yet
Development

No branches or pull requests

2 participants