-2

I have trouble using bubble-sort on my ArrayList sorting them in an alphabetical order.

I tried to read up (and copy) some of the bubble sorting methods i've found online but nothing has worked so far.

private void listUsers() {
    int x;
    User temp;
    User temp2;
    if (users.isEmpty()) {
        System.out.println("Error: no users in register");
    } else {
        for (User item : users) {               
            sortedUsers.add(item);
            if (!sortedUsers.isEmpty()) {
                for (x = 0; x < sortedUsers.size(); x ++) {
                    if (sortedUsers.get(x).getName().compareTo(sortedUsers.get(x+1).getName()) > 0) {
                        temp = sortedUsers.get(x);
                        temp2 = sortedUsers.get(x+1);
                        sortedUsers.set(x, temp2);
                        sortedUsers.set(x+1, temp);
                    }
                }
            }
            //System.out.println(item);
            System.out.println(item);

        }
    }
}

As of now i'm getting a java.lang.IndexOutOfBoundsException, I understand that with the x+1 i'm trying to get indexes without items but don't really understand how to fix it.

  • line `if (sortedUsers.get(x).getName().compareTo(sortedUsers.get(x+1).getName()) > 0)` you are checking value from `x+1` index, that might be out fo bounds – Bartosz Wardziński Jan 15 '19 at 16:05

1 Answers1

0

Use for (x = 0; x < sortedUsers.size()-1; x ++)

You're comparing each item with the next one. So you can't extend beyond the penultimate (n-1th) one when doing the comparison compareTo(sortedUsers.get(x+1).

user1717259
  • 2,429
  • 5
  • 26
  • 38