java - 希尔排序一个语句使速率慢了上百倍
高洛峰
高洛峰 2017-04-17 17:31:12
0
2
647
private static boolean less(Comparable v, Comparable w) {
    return v.compareTo(w) < 0;
}

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

public static void sort(Comparable[] a) {
    int n = a.length;
    int h = 1;
    while (h < n / 3) {
        h = 3 * h + 1;
    }
    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 /= 3;
    }
}
public static void sort(Comparable[] a) {
    int n = a.length;
    int h = 1;
    while (h < n / 3) {
        h = 3 * h + 1;
    }
    while (h >= 1) {
        for (int i = h; i < n; i++) {
            for (int j = i; j >= h ; j -= h) {
                if (less(a[j], a[j - h])) {
                    exch(a, j, j - h);
                }
            }
        }
        h /= 3;
    }
}

第二个sort方法只是把 if 语句从for循环的判断语句中取出,为什么排序速度会慢了上百倍呀?

高洛峰
高洛峰

拥有18年软件开发和IT教学经验。曾任多家上市公司技术总监、架构师、项目经理、高级软件工程师等职务。 网络人气名人讲师,...

reply all(2)
迷茫

The for loop in the first function ran to less() == true就退出了,第二个会一直循环运行到j<h才退出。比较显然也是要花时间的,可以当作一种运算。第二个函数在less() == true and made many useless comparisons, and the complexity directly degraded to O(n^2).

伊谢尔伦

Disregarding the issue of speed, your way of writing is not equivalent. The number of executions of the first loop in the innermost loop must be

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!