我需要调试我的代码的帮助。它一直在犯错误,我不知道在哪里。这是我的选择排序方法:
private void selectionSort() {
int best = 0;
int j = 0;
SortableRobot bestSoFar = botList.get(0);
for(int i = 0;i<botList.size();i++) {
int[] temp = botList.get(j).getLocation();
for(int x = j;x<botList.size();x++) {
if(botList.get(j).compareTo(botList.get(x)) < 0) {
// botList.get(j).moveToLocation(botList.get(x).getLocation());
// botList.get(x).moveToLocation(temp);
bestSoFar = botList.get(x);
best = x;
}
}
SortableRobot tempbot = botList.get(j);
botList.set(best,tempbot);
botList.set(j, bestSoFar);
j++;
}
}
最佳答案
问题是必须在每次迭代的开始时设置变量bestSoFar
。
此修改使其在我的测试中起作用:
import java.util.ArrayList;
import java.util.List;
public class Test {
private List<SortableRobot> botList;
public static void main(String[] args) {
new Test();
}
public Test() {
botList = new ArrayList<SortableRobot>();
botList.add(new SortableRobot(5));
botList.add(new SortableRobot(3));
botList.add(new SortableRobot(4));
botList.add(new SortableRobot(1));
botList.add(new SortableRobot(2));
System.out.println("before sort: " + botList);
selectionSort();
System.out.println("after sort: " + botList);
}
private void selectionSort() {
int best = 0;
int j = 0;
SortableRobot bestSoFar = botList.get(0);
for (int i = 0; i < botList.size(); i++) {
bestSoFar = botList.get(j);// EDITED HERE the best bot so far has to be set to the current bot in the beginning of every iteration
// int[] temp = botList.get(j).getLocation();
for (int x = j; x < botList.size(); x++) {
if (botList.get(j).compareTo(botList.get(x)) < 0) {
// botList.get(j).moveToLocation(botList.get(x).getLocation());
// botList.get(x).moveToLocation(temp);
bestSoFar = botList.get(x);
best = x;
}
}
SortableRobot tempbot = botList.get(j);
botList.set(best, tempbot);
botList.set(j, bestSoFar);
j++;
}
}
private class SortableRobot implements Comparable<SortableRobot> {
private int sortIndex;
public SortableRobot(int sortIndex) {
this.sortIndex = sortIndex;
}
public String toString() {
return "SortableRobot[" + sortIndex + "]";
}
public int compareTo(SortableRobot o) {
return Integer.compare(sortIndex, o.sortIndex);
}
}
}
输出为:
before sort: [SortableRobot[5], SortableRobot[3], SortableRobot[4], SortableRobot[1], SortableRobot[2]]
after sort: [SortableRobot[5], SortableRobot[4], SortableRobot[3], SortableRobot[2], SortableRobot[1]]