Sorting array list in Java

后端 未结 4 957
悲哀的现实
悲哀的现实 2021-01-14 06:22

I have following class. In this, Iris is another class with some attributes.

public class Helper {

    Iris iris;
    double distance;

    public Helper(Ir         


        
相关标签:
4条回答
  • 2021-01-14 06:56

    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);
        }
    })
    
    0 讨论(0)
  • 2021-01-14 06:57

    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));
    
        }
    }
    
    0 讨论(0)
  • 2021-01-14 07:00

    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.

    0 讨论(0)
  • 2021-01-14 07:02

    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);
       }
    }
    
    0 讨论(0)
提交回复
热议问题