Sorting array list in Java

后端 未结 4 956
悲哀的现实
悲哀的现实 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 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);
       }
    }
    

提交回复
热议问题