简体   繁体   English

插入排序,比较次数

[英]Insertion sort, number of comparisons

Hi all for an assignment we must count the number of comparisons for a number of algorithms. 大家好,对于一项作业,我们必须计算多种算法的比较次数。 I'm using the code in the book "Algorithms" by Sedgewick & Wayne. 我正在使用Sedgewick&Wayne撰写的“算法”一书中的代码。 I don't see where my code is wrong actually... As soon we going to compare something I count my comparison... 我实际上看不出我的代码在哪里错误...我们马上比较一下我计算的比较...

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

the less method which I use: 我使用的较少方法:

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

It must pass this test 它必须通过此测试

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

those two should be equal.... 那两个应该相等...

The isSorted methods: 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;
    }

Someone ideas about this? 有人对此有想法吗? Help will be appreciated! 帮助将不胜感激!

Number of comparisons should be exactly N*(N-1)/2. 比较次数应精确为N *(N-1)/ 2。 Maybe you mess with comparisons field in somewhere else, so I would advise to use local variable instead: 也许您在其他地方遇到了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
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM