繁体   English   中英

选择排序中的比较次数?

[英]Number of comparisons in selection sort?

我的程序使用选择排序处理比较次数。 它返回错误的伴奏数量。 哪里出错了?

我的演示:

    ArrayI[] ints = new ArrayI[5];


    ints[0] = new ArrayInts(3);
    ints[1] = new ArrayInts(9);
    ints[2] = new ArrayInts(6);
    ints[3] = new ArrayInts(1);
    ints[4] = new ArrayInts(2);




    SelectionSort.selectionSort(myInts);

    System.out.println(" ");

    System.out.println("Sorted array: ");

    for(ArrayI ints:myInts){
        System.out.println(ints);
    }

    System.out.println(" ");

    System.out.println("Number of comparisons: " + SelectionSort2.selectionSort2(ints));  

这是因为,您在内部循环之外增加了比较。 因此,比较的值等于您的外循环运行的次数。 将增量移动到内部循环:

而且您真的不需要min变量。 您可以将交换逻辑移到if块内。 您应该将代码修改为:

for(int index = 0; index < data.length-1; index++) {

    for(int scan = index+1; scan < data.length; scan++) {
        comparisons++;  // Each inner loop does one comparison

        if(data[scan].compareTo(data[min]) < 0) {
            temp = data[scan];
            data[scan] = data[index];
            data[index] = temp;
        }
    }   
}

我真的不明白您创建ArrayInts类的要点。 那完全没有必要。 您可以简单地使用Integer包装器类。 仅供参考,您有一个Arrays#sort(Object[])方法,该方法为您进行排序。

暂无
暂无

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

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