插入排序,比较次数

时间:2015-03-21 21:09:42

标签: java algorithm sorting insertion-sort

大家好,我们必须计算许多算法的比较次数。我正在使用Sedgewick& Sons出版的“算法”一书中的代码。韦恩。我实际上并没有看到我的代码出错的地方......我们很快就会比较一些我认为比较的东西......

public long sort(Comparable[] a) {
        if (a == null) {
            throw new IllegalArgumentException("argument 'array' must not be null.");
        }
        int N = a.length;
        for (int i = 0; i < N; i++) {
            for (int j = i; j > 0; j--) {
                this.comparisons++;
                if(less(a[j], a[j-1]))
                    exch(a, j, j-1);      
            }
            assert isSorted(a, 0, i);
        }
        assert isSorted(a);
        return this.comparisons;
    }

我使用的方法越少:

private boolean less(Comparable v, Comparable w) {
        return (v.compareTo(w) < 0);
    }

必须通过此测试

Integer[] array = {4, 2, 1, 3, -1};
        Comparable[] arrayClone1 = array.clone();
        Comparable[] arrayClone2 = array.clone();
        long nbCompares1 = i.sort(arrayClone1);
        long nbCompares2 = i.sort(arrayClone2);
        System.out.println("1" + nbCompares1);
        System.out.println("2" + nbCompares2);

这两者应该是平等的......

isSorted方法:

 private boolean isSorted(Comparable[] a) {
        System.out.println("here");
        return isSorted(a, 0, a.length - 1);
    }

    // is the array sorted from a[lo] to a[hi]
    private boolean isSorted(Comparable[] a, int lo, int hi) {
        System.out.println("here1");
        for (int i = lo + 1; i <= hi; i++)
            if (less(a[i], a[i-1])) return false;
        return true;
    }

有人对此有何看法?帮助将不胜感激!

1 个答案:

答案 0 :(得分:1)

比较次数应该恰好是N *(N-1)/ 2。也许你在其他地方混淆comparisons字段,所以我建议改为使用局部变量:

public long sort(Comparable[] a) {
        if (a == null) {
            throw new IllegalArgumentException("argument 'array' must not be null.");
        }
        int N = a.length;
        int comparisonsCount = 0; // use this instead
        for (int i = 0; i < N; i++) {
            for (int j = i; j > 0; j--) {
                comparisonsCount++; // edit here
                if(less(a[j], a[j-1]))
                    exch(a, j, j-1);      
            }
            assert isSorted(a, 0, i);
        }
        assert isSorted(a);
        return comparisonsCount; // and here
    }