我对java很陌生,我正试图使一种泡泡排序工作在双倍的环境中。出于某种原因,分拣对我来说是一个真正的难题。下面是代码,但它什么也没做。它不会出错,但也不会排序。我觉得这是个愚蠢的语法错误。我的目标是使项目文件中的项的值降序排序。
public static ArrayList<Item> sortValue(ArrayList<Item> example)
{
for (int i = 0; i < example.size() - 1; i++ )
for (int j = 0; j < example.size() - 1 - i; j++)
if (example.get(j).getValue() == (example.get(j+1).getValue())) {
example.add(j+1, example.remove(j));
}
return example;
}我在另一个方法的开头调用该方法:
sortValue(example);并且仍然得到以下结果:
books 2.0 2.0 2 2
shoes 1.0 1.0 1 1
sword 10.0 10.0 10 10不漂亮,但基本上10岁应该排在第一位。感谢你的建议!
发布于 2018-04-20 13:43:14
你想要做的事情叫做BubbleSort,但是你遗漏了一些东西:
public static ArrayList<Item> sortValue(ArrayList<Item> example) {
Item aux = null;
for(int i = 0; i < example.size(); i++){
for(int j = 0; j < example.size() - 1; j++){
if(example.get(j).getValue() > example.get(j + 1).getValue()){
aux = example.get(j);
example.set(j, example.get(j + 1));
example.set(j + 1, aux);
}
}
}
return example;
}注意,我们使用一个名为aux的局部变量来存储列表j位置,然后将其更新为j + 1值。还请注意,我们使用的是> (大于)比较器,而不是==。
https://stackoverflow.com/questions/49942717
复制相似问题