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