开发者社区 问答 正文

希尔排序速率问题

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循环的判断语句中取出,为什么排序速度会慢了上百倍呀?

展开
收起
蛮大人123 2016-03-11 19:00:34 1945 分享 版权
1 条回答
写回答
取消 提交回答
  • 我说我不帅他们就打我,还说我虚伪

    第一个函数里面的for循环运行到less() == true就退出了,第二个会一直循环运行到j

    2019-07-17 18:59:56
    赞同 展开评论
问答分类:
问答地址: