我的程序处理使用选择排序的比较次数。它返回错误的comp数。 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));
答案 0 :(得分:4)
那是因为,你正在增加内循环之外的比较。因此,比较的值将等于外循环运行的次数。将增量移动到内循环:
你真的不需要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[])
方法,可以为您排序。