简体   繁体   English

计算MergeSort Java的比较数

[英]Counting Number of Comparisons for MergeSort Java

I am having trouble counting the number of comparisons for mergesort in Java. 我在计算Java中的mergesort比较次数时遇到麻烦。 Below is my code. 下面是我的代码。 Not sure if I'm placing it in the wrong spot, etc. 不知道我是否将其放置在错误的位置等。

Any help is definitely appreciated, thanks. 任何帮助都非常感谢,谢谢。

private static int merge(int[] intArray, int first, int n1, int n2) {
    int numComparisons = 0;
        int[] temp = new int[n1+n2];
        int copied = 0, copied1 = 0, copied2 = 0;
        while((copied1 < n1) && (copied2 < n2)){
            if (intArray[first + copied1] < intArray[first + n1 + copied2]) {
                temp[copied++] = intArray[first + copied1++];
            }
            else {
                temp[copied++] = intArray[first + n1 + copied2++];
            }

        }

        while(copied1 < n1)     {
            temp[copied++] = intArray[first + copied1++];
        }
        while(copied2 < n2)     {
            temp[copied++] = intArray[first + n1 +copied2++];
        }


        for(int i = 0; i < n1+n2; i++) {
            numComparisons++;
            intArray[first + i] = temp[i];  
        }

        return numComparisons;
    }


    public static int mergeSortComparisons(int[] intArray, int first, int last){
        int n1, n2;
        if (last > 1){

            n1 = last/2;
            n2 = last - n1;

            mergeSortComparisons(intArray, first, n1);
            mergeSortComparisons(intArray, first + n1, n2);

            merge(intArray, first, n1, n2);
        }

        return first;
    }

If you want to count the number of comparisons, take the comparison step, refactor it to a method, and instrument the method. 如果要计算比较次数,请执行比较步骤,将其重构为方法,然后对方法进行检测。 You are incrementing numComparisons in the wrong place. 您在错误的位置增加了numComparisons

private static boolean lessThan(int[] ia, int leftIndex, int rightIndex) {
    numComparisons++;
    return ia[leftIndex] < ia[rightIndex];
}

Use that instead of your comparison line near the top of merge . 用它代替merge顶部附近的比较线。

Also, write JUnit tests to ensure that your sort works. 另外,编写JUnit测试以确保排序有效。 Finally, do you need to have all your methods be static? 最后,您是否需要使所有方法都是静态的?

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

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