我需要编写自己的方法选择排序,而不使用Java中的Collections.sort()。这是我目前的代码,我似乎无法弄清楚如何在列表中实际交换位置。非常感谢任何帮助!
ArrayList<Integer> ListOfNumbers = new ArrayList(8);
ListOfNumbers.add(9);
ListOfNumbers.add(19);
ListOfNumbers.add(2);
ListOfNumbers.add(1231);
ListOfNumbers.add(89);
ListOfNumbers.add(17);
ListOfNumbers.add(3);
ListOfNumbers.add(1);
for(int i=0; i<ListOfNumbers.size(); i++)
{
int CurrentMinimum = i;
for (int j=i+1; j<ListOfNumbers.size(); j++)
{
if(ListOfNumbers.get(j) < ListOfNumbers.get(i))
{
CurrentMinimum = j;
}
if (CurrentMinimum != i)
{
int temp;
temp = i;
i = CurrentMinimum;
CurrentMinimum = temp;
System.out.println(ListOfNumbers);
}
}
}
答案 0 :(得分:1)
您可以使用List Interface中的set方法交换值。
set(int index, E element)
基本上做以下事情:
int temp = list.get(i);
list.set(i, list.get(j));
list.set(j, temp);
答案 1 :(得分:0)
在数组列表al中使用索引b置换索引a:
希望它会有所帮助。
您的排序算法存在问题:
/* find the next minimum */
for(int j=i+1; j<ListOfNumbers.size(); j++)
{
if(ListOfNumbers.get(j) < ListOfNumbers.get(CurrentMinimum)) // <<<<<
{
CurrentMinimum = j;
}
}
/ *然后,如有必要,置换* /
temp = ListOfNumbers.remove(i);
ListOfNumbers.add(i, ListOfNumbers.remove(CurrentMinimum-1)); // -1 because of previous remove
ListOfNumbers.add(CurrentMinimum,temp);
答案 2 :(得分:-1)
你可以使用
List<Integer> ListOfNumbers = new ArrayList<Integer>();
list.add(1);
list.add(2);
list.add(3);
list.add(4);
Collections.swap(ListOfNumbers, 0, 3);