0

I'd like to be able to modify this code so that it uses Knuth's H sequence instead of this one. If anyone could help, I'd greatly appreciate it.

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);
    }
}
templatetypedef
  • 362,284
  • 104
  • 897
  • 1,065
  • "Knuth's H sequence" is not a term I've ever heard, and Google does not help much either. You may need to explain what it is that you want to do. Also, I get the feeling that the question should be tagged [homework]. – Igor ostrovsky Apr 28 '11 at 08:42
  • @Igor - shellsort depends on a certain "sequence", the original recommendation was 1,2,4,8,16,...,2^k and Knuth (and others) developed other sequences to improve overall time complexity. The name is not *H sequence* but the idea is part of most shellsort articles on the web (wikipedia et.al.) – Andreas Dolk Apr 28 '11 at 08:47
  • @Andreas_D for the 1,2,4,8,16 sequence I believe this may be correct? [link]http://pastebin.com/W8PmgVdA – Alexander Berndt Apr 28 '11 at 09:33

1 Answers1

0

For the sequence 1,2,4,8,16 I believe this may be correct? Replacing the version0 class with this:

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]);
        }
    }
}