Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Java Bubble-Sort Not checking the last loop through

I am trying to sort an ArrayList but hit a wall at the moment. Below, I have a getId() function that retrieves the id of a member. I want to sort the ArrayList by member id. I have checked a afew good articles on this and implemented the following :

e.g (before sort)
11
22
33
44
55
66
77
88
99
00

e.g (after sort)
00
11
22
33
44
55
66
77
88
99

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Member temp;

for (int i = 0; i < members.size(); i++) {
    Member s = members.get(i);
    System.out.println("S: "+s.getId());
            
    for (int j=0; j < members.size()-1; j++) {
        Member t = members.get(j+1);
        System.out.println("T: "+t.getId());
                
        if (s.getId() > t.getId()) {
        temp = s;
        s = t;
        t = temp;
        }
     }
  }
}

I did the printout statements above to trace the root cause but still trying to figure out the error.

>Solution :

The code for swapping is wrong:

if (s.getId() > t.getId()) {
   temp = s;
   s = t;
   t = temp;
}

Here you only swap s with t, but the data underlying members are not affected. The correct one:

for (int i = 0; i < members.size() - 1; i++) {
     for (int j = 0; j < members.size() - i - 1; j++) {
         Member s = members.get(j);
         Member t = members.get(j+1);
         if (s.getId() > t.getId()) {
             Collections.swap(members, j, j+1);
         }
    }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading