I am trying to do a selection sort with the years on an ArrayList of movies, and with this code, I get the years in the right descending order, but the titles and studio names do not correspond with the year in the output. How can I get the titles, studio names, and years to be together?
ArrayList:
ArrayList<Movie3> myMovies = new ArrayList<Movie3>();
myMovies.add(new Movie3("The Muppets Take Manhattan", 2001, "Columbia Tristar"));
myMovies.add(new Movie3("Mulan Special Edition", 2004, "Disney"));
myMovies.add(new Movie3("Shrek 2", 2004, "Dreamworks"));
myMovies.add(new Movie3("The Incredibles", 2004, "Pixar"));
myMovies.add(new Movie3("Nanny McPhee", 2006, "Universal"));
myMovies.add(new Movie3("The Curse of the Were-Rabbit", 2006, "Aardman"));
myMovies.add(new Movie3("Ice Age", 2002, "20th Century Fox"));
myMovies.add(new Movie3("Lilo & Stitch", 2002, "Disney"));
myMovies.add(new Movie3("Robots", 2005, "20th Century Fox"));
myMovies.add(new Movie3("Monsters Inc.", 2001, "Pixar"));
Sorting:
int i, k, posmin;
int temp;
for (i = b.size()-1; i >= 0; i--) {
posmin = 0;
for (k=0; k <= i; k++) {
if (b.get(k).getYear() <= b.get(posmin).getYear()) posmin = k;
}
temp = b.get(i).getYear();
b.get(i).setTitle(b.get(posmin).getTitle());
b.get(i).setYear(b.get(posmin).getYear());
b.get(i).setStudio(b.get(posmin).getStudio());
b.get(posmin).setYear(temp);
}
EDIT: This is the code I based it off of - it sorts the titles, and it works perfectly fine.
int i, k, posmax;
String temp;
for (i = b.size()-1; i >= 0; i--) {
posmax = 0;
for (k=0; k <= i; k++) {
if (b.get(k).getTitle().compareTo(b.get(posmax).getTitle()) < 0) posmax = k;
}
temp = b.get(i).getTitle();
b.get(i).setTitle(b.get(posmax).getTitle());
b.get(i).setYear(b.get(posmax).getYear());
b.get(i).setStudio(b.get(posmax).getStudio());
b.get(posmax).setTitle(temp);
}
Quick fix: You need to swap all data in the Object, not only the year.
For example, when the 2nd round in your sorting algorithm, you will result in swapping Movie3("The Muppets Take Manhattan", 2001, "Columbia Tristar")
and new Movie3("Robots", 2005, "20th Century Fox")
. Because you only swap the years (set all data to the last but only set year back to the unordered list), so it will end with Movie3("The Muppets Take Manhattan", 2005, "Columbia Tristar")
and Movie3("The Muppets Take Manhattan", 2001, "Columbia Tristar")
. Therefore, your Robots
movie is disappeared.
Better solution: You can swap the reference instead of set all data in the Object.
Since there are references stored in the ArrayList, you can just swap those references to swap them.
Movie3 tmp = b.get(i);
b.set(i, b.get(posmin));
b.set(posmin, tmp);
It would be better in this case.