So in a class Tournament, I have an ArrayList of that contains (String Name, int handicap)
There is a method alphabeticSort() which sorts the list of players alphabetically by name. I have to use insertion sort for it.
Below I tried to adapt insertion sort algorithm I know to make it work but both lines of
players.add(j+1)
gives me an error saying "the left hand side of an assignment must be a variable." I understand what that means but I am unable to come up with a solution for it.
public void alphabeticSort() {
for(int i = 1; i < players.size(); i++) {
String key = players.get(i).getName();
int j = i - 1;
while (j >= 0 && key.compareTo(players.get(i).getName()) < 0) {
players.add(j+1) = players.get(j);
j--;
}
players.add(j+1) = key;
}
Im not sure how to resolve this. Am I even on the right track? Please help. Any help appreciated
EDIT: I have changed the first instance of
players.add(j+1) = players.get(j);
to
players.set(j+1, players.get(j));
Do I do the same for the second instance (last line)
Also I have found out that the line
while (j >= 0 && key.compareTo(players.get(i).getName()) < 0)
is wrongs as in the actual insertion sort its supposed to be
while(j >= 0 && arr[k]> backup)
BUT im not sure how to implement that with Strings, as you cannot use operators on strings. HELP???
EDIT 2:
JUnit test which is supposed to test if it works
public void testAlphabeticSort() {
int [] par = {3,4,5,4,5,3,4,3,5,3,4,5,4,3,4,5,4,3};
int [] scores1 = {3,4,3,5,3,4,4,3,5,3,3,4,3,4,3,4,3,4};
int [] scores2 = {4,4,3,5,3,4,4,3,5,3,3,4,3,4,3,4,3,4};
int [] scores3 = {3,4,3,5,3,4,4,3,5,3,3,4,3,4,3,4,3,5};
Tournament T = new Tournament(par);
T.enter("Scott", 1, scores3);
T.enter("Norman", 2, scores1);
T.enter("Palmer", 4, scores2);
T.alphabeticSort();
ArrayList<Player> sortedPlayers = T.getPlayers();
Player player1 = new Player("Norman", 2, scores1);
Player player2 = new Player("Palmer", 4, scores2);
Player player3 = new Player("Scott", 1, scores3);
assertTrue(sortedPlayers.get(0).equals(player1));
assertTrue(sortedPlayers.get(1).equals(player2));
assertTrue(sortedPlayers.get(2).equals(player3));
}