/**
* Sorts the list of players alphabetically by name.
* Adapt insertion sort algorithm.
* You can assume that no two players have the same name.
* Question T1. Adapting insertion sort for this method
* could yield efficiencies relative to some other approaches
* for some important special cases.
* Do you agree and if so why? Write about 6 to 10 lines.
*/
public void alphabeticSort() {
Player temp;
for (int i = 0; i < players.size(); i++) {
for (int j = players.size() - 1; j > i; j--)
if (players.get(i).compareTo(players.get(j)) < 0) {
temp = players.get(i);
players.set(i, players.get(j));
players.set(j, temp);
}
}
}
我一直在努力,努力,但我有一些困难,试图比较,你不能使用<
和>
用<Player>
类ArrayList
。我们也无法使用任何Collection.sort
进口。
向正确的方向推进将是巨大的!
如果要按名称比较玩家,请按对象名称比较对象:
if (players.get(i).getName().compareTo(players.get(j).getName()) < 0) {
如果您被允许使用Collections.sort
,那么实现可能会简单得多而且更好:
public void alphabeticSort() {
Collections.sort(players, (p1, p2) -> p1.getName().compareTo(p2.getName()));
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句