I have following class. In this, Iris is another class with some attributes.
public class Helper {
Iris iris;
double distance;
public Helper(Iris iris, double distance) {
this.iris = iris;
this.distance = distance;
}
}
I want to sort an array list of this (i.e List < Helper > helperList), descending based on distance parameter. I have written the following method but it is not working.
public void sort(){
for(int k=0; k < helperList.size(); k++)
{
double distance = helperList.get(k).distance;
for(int l=0; l < helperList.size(); l++)
{
Helper temp = helperList.get(l);
if( distance < temp.distance )
{
helperList.set(l, helperList.get(k));
helperList.set(k, temp);
}
}
}
}
Can anybody suggest a solution?
[1,2]. fork = 0, l = 1, becauselist.get(1) > 1, you swap, giving[2,1]. Then fork = 1, l = 0you swap again. You should compare each element only to those on one side of it.k+1instead of 0 it works. However, the proper way would be to create aComparatormeeting your needs and use a library sort. Or implement one of the classical sorting algorithms.