I am trying to sort an arrayList in two different ways, one by the areas of the objects inside the arrayList, and two, by the name(shape1, shape2) of the objects in the arrayList. The objects look like this when I print them into a file: shape1: (points, radius, etc…) area = 0.0 and the shapes keep going. I tried looking at other asked questions that are similar but all answered using Collections.sort. I am not sure I am supposed to be using this method. Here’s some code I’m working with to give you an idea:
for (int i =0; i <shapes.size();i++){
for (int j = 1; j<shapes.size(); j++){
if (shapes.get(i).getShape().area() > shapes.get(j).getShape().area())
{
//
}
else
{
//
}
}
}
I’m not sure how I should go about doing this. Any pointers? For the sorting by name I have to use:
shapes.get(i).getName()
Since this is homework, I will not post any code.
If you are not allowed to use
Arrays.sort, you can implement Selection Sort – it is very simple, and you have the beginnings of it written in your code already. The idea is on each iteration of the outer loop onito pick the smallest element in the segment fromitoshapes.size()using the inner loop onj, and place that element at thei-th position of your array. Your inner loop should look like this:Now based on your
ifcondition you either swapj-th element withi-th, or keep it in place and move on.For sorting strings, use
compareTomethod in yourifcondition.