【问题标题】:Number of comparisons in selection sort?选择排序中的比较次数?
【发布时间】:2013-09-01 06:06:09
【问题描述】:

我的程序使用选择排序处理比较次数。它返回错误的组合数。 comp哪里出了问题?

我的演示:

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

【问题讨论】:

  • 为什么你有不同的计算比较次数的方法?你不能用第一种方法本身来做吗?
  • ArrayInts 类的意义何在?为什么不能简单地使用Integer
  • @seh 不是重复的 - 这些问题与两种不同的排序方法有关。
  • 啊,你是对的。我看到每个作者都是同一个作者,还以为他发了两次。我撤回了那票。我会出于不同的原因投票关闭它。

标签: java arrays class sorting


【解决方案1】:

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

你真的不需要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[]) 方法,它会为您进行排序。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-09-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-10
    • 1970-01-01
    • 2012-06-01
    相关资源
    最近更新 更多