I have following class. In this, Iris is another class with some attributes.
public class Helper {
Iris iris;
double distance;
public Helper(Ir
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);
}
})
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));
}
}
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.
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);
}
}