Reputation: 1821
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?
Upvotes: 3
Views: 4819
Reputation: 2622
Why don't you get your Helper
class to implement Comparable
interface and then use the in-built sort method offered by the Collections class.
Collections.sort(helperList)
I think that would solve the problem. Plus, this sort
method is stable.
http://docs.oracle.com/javase/7/docs/api/java/util/Collections.html#sort%28java.util.List%29
http://docs.oracle.com/javase/7/docs/api/java/lang/Comparable.html
Implementing Comparable interface:
public class Helper implements Comparable{
Iris iris;
double distance;
public Helper(Iris iris, double distance) {
this.iris = iris;
this.distance = distance;
}
public int compareTo(Helper other) {
return new Double(this.distance).compareTo(new Double(other.distance));
}
}
Upvotes: 17
Reputation: 753
Divya's answer is good, but if you don't want to implement Comparable interface, following might be help:
Collections.sort(helperList, new Comparator<Helper>() {
public int compare(Helper helper1, Helper helper2) {
return Double.compare(helper1.distance, helper2.distance);
}
})
Upvotes: 4
Reputation: 2743
The problem is that the loop looses track of where the distance index is located after it has been swapped. This algorithm should work fine.
for(int k = 1; k < helperList.size(); k++) {
double distance = helperList.get(k).distance;
int j = k - 1;
boolean done = false;
while(!done) {
Helper temp = helperList.get(j);
if(temp.distance < distance) {
helperList.set(j+1, temp);
j = j - 1;
if(j < 0) {
done = true;
}
} else {
done = true;
}
helperList.set(j+1, value);
}
}
Upvotes: 1
Reputation: 5663
The article on bubble sort on Wikipedia contains pseudo code and also some optimized versions. Compare with that one to see where you are going wrong.
Bubble sort is one of the most obvious sorting algorithms, but not exactly the most efficient. Why don't you let the platform do the sort? java.util.Collections
contains a sort
method that lets you supply your own Comparator
. All that comparator has to do is decide which of two Helper
instances should come first.
Upvotes: 0