gpt4 book ai didi

java - Java Arraylist 中的选择排序

转载 作者:行者123 更新时间:2023-12-02 09:16:12 27 4
gpt4 key购买 nike

我需要帮助调试我的代码。它一直在犯错误,我找不到哪里。这是我的选择排序方法:

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]]

关于java - Java Arraylist 中的选择排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58968303/

27 4 0
文章推荐: java - 将 ArrayList 转换为字符串