copernicon1543 - 7 months ago 46

Java Question

`/**`

* 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);

}

}

}

I've been trying and trying but I am having some difficulty trying to compare as you are unable to use

`<`

`>`

`<Player>`

`ArrayList`

`Collection.sort`

A push in the right direction would be great!

Answer

If you want to compare players by names, then compare the objects by their names:

```
if (players.get(i).getName().compareTo(players.get(j).getName()) < 0) {
```

If you're allowed to use `Collections.sort`

, then the implementation could be a lot simpler and better:

```
public void alphabeticSort() {
Collections.sort(players, (p1, p2) -> p1.getName().compareTo(p2.getName()));
}
```

Source (Stackoverflow)