0

我希望能够修改此代码,以便它使用 Knuth 的 H 序列而不是这个。如果有人可以提供帮助,我将不胜感激。

public class ShellSort {
    static int iterations = 0;
    static void insert(double[] a, int h, int r, double v) {
            int i = r - h;
            while (i >= 0 && a[i] > v) {
                a[i+h] = a[i]; i = i - h;
                iterations ++;
            }
            a[i+h] = v;
    }

    static void version0(double[] a, int p, int q) {
        int h;
        h = 1;
        for (int i = p + h; i < q; i++) {
            insert(a, h, i, a[i]);
        }
    }

    public static void main(String[] argv) {
        int size = Integer.parseInt(argv[0]);
        double a[] = new double[ size ];
        for (int i = 0; i < a.length; i++) {
            a[ i ] = Math.random();
            System.out.println(i + " " + a[ i ]);
        }

        version0(a, 0, a.length);

        for (int i = 0; i < a.length; i++) {
            System.out.println(i + " " + a[ i ]);

        }
        System.out.println("Iterations "+ iterations);
    }
}
4

1 回答 1

0

对于序列 1,2,4,8,16 我相信这可能是正确的?用这个替换 version0 类:

static void version1(double[] a, int p, int q) {
int h;
for (h = 1; h <= a.length / 2; h = 2 * h)
/* nothing */ ;
    for ( ; h > 0; h = h / 2) {
        for (int i = p + h; i < q; i++) {
            insert(a, h, i, a[i]);
        }
    }
}
于 2011-04-29T08:52:50.150 回答