I am having issues (using a modified version of SelectionSort) to sort the ArrayList
of Car
objects from lowest MPG
to greatest MPG
. Here is my code:
public ArrayList<Car> getSortedByMPG(){
ArrayList<Car> bestMPG = new ArrayList<Car>();
bestMPG.addAll(myCars);
int smallestIndex;
Car smallest;
Car smallest1;
double smallestMPG;
double smallestMPG1;
for (int curIndex = 0; curIndex < bestMPG.size(); curIndex++) {
smallest = bestMPG.get(curIndex);
smallestMPG = smallest.getMPG();
smallestIndex = curIndex;
for (int i = curIndex + 1; i < bestMPG.size(); i++) {
smallest1 = bestMPG.get(i);
smallestMPG1 = smallest1.getMPG();
if (smallestMPG > smallestMPG1) {
smallest = bestMPG.get(i);
smallestIndex = i;
}
}
if (smallestIndex != curIndex) {
Car temp = bestMPG.get(curIndex);
bestMPG.set(curIndex, bestMPG.get(smallestIndex));
bestMPG.set(smallestIndex, temp);
}
}
return bestMPG;
}
There is a tester class for this method, however, I do not want to post it (to avoid getting trolled for code dumping). I have worked on this for a few hours now and cannot figure out why this code is not sorting. If anyone can offer any advice it would be much appreciated.
EDIT: Thank you all for the responses. I realize I did not do the proper research beforehand, but that is why I come to StackOverflow! You guys teach me things daily.
Here is how I solved it, thanks to Aomine:
public ArrayList<Car> getSortedByMPG(){
ArrayList<Car> bestMPG = new ArrayList<Car>();
bestMPG.addAll(myCars);
Collections.sort(bestMPG, Comparator.comparingDouble(Car::getMPG));
return bestMPG;
}
one of several ways to sort your list is by using the List.sort
method and passing in a comparator object. Ie:
bestMPG.sort(Comparator.comparingDouble(Car::getMpg));
then you can just return bestMPG
.
If I understood your question, you can use Collections.sort
ArrayList<Car> bestMPG = new ArrayList<Car>();
Collections.sort(bestMPG, new Comparator<Car>() {
public int compare(Car c1, Car c2) {
Double mpg1 = c1.getMpg();
Double mpg2 = c2.getMpg();
return mpg1.compareTo(mpg2);
}
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.