0

I got an ArrayList which contains next data: coordX , coordY , length , position ( position can be of 3 types : vertical , horizontal or 1x1 ). Using insertion method , I sort this descending by length . How can i give priority in case if length is equal for that value of length who has the horizontal position.For given input :

(1;0)  ,  length = 2  ,  position - vertical
(1;6)  ,  length = 4  ,  position - horizontal
(3;4)  ,  length = 3  ,  position - horizontal
(3;6)  ,  length = 1  ,  position - 1x1
(4;0)  ,  length = 1  ,  position - 1x1
(5;3)  ,  length = 2  ,  position - horizontal
(6;7)  ,  length = 2  ,  position - vertical
(7;5)  ,  length = 2  ,  position - horizontal

the output should be :

(1;6)  ,  length = 4  ,  position - horizontal
(3;4)  ,  length = 3  ,  position - horizontal
(5;3)  ,  length = 2  ,  position - horizontal
(7;5)  ,  length = 2  ,  position - horizontal
(1;0)  ,  length = 2  ,  position - vertical
(6;7)  ,  length = 2  ,  position - vertical
(3;6)  ,  length = 1  ,  position - 1x1
(4;0)  ,  length = 1  ,  position - 1x1

This is what i have at the moment :

public static void insertionSort(ArrayList<sort> srt) {
        int i,j;
        for (i = 1; i < srt.size(); i++) {
            sort tmp = srt.get(i);
            j = i;
            while ((j > 0) && (srt.get(j - 1).length< tmp.length)) {
                srt.set(j, srt.get(j - 1));
                j--;
            }
            srt.set(j, tmp);
        }
        for(sort e : srt) {
            System.out.println("("+e.coordX+";"+e.coordY+")"+"  ,  length= "+e.length+"  ,  position - "+e.pozitie);
        }

}

This part of code is responsabile only for sorting by the length.

Alessandro
  • 35
  • 5
  • Does this answer your question? [How to sort by two fields in Java?](https://stackoverflow.com/questions/4805606/how-to-sort-by-two-fields-in-java) – Johannes Kuhn Apr 07 '20 at 22:11

1 Answers1

1

Try the following:

You need to check first on the length and then if they are equal, check on the position.

            while ((j > 0) && (srt.get(j - 1).length < tmp.length
                    || (srt.get(j - 1).length == tmp.length
                            && srt.get(j - 1).position
                                    .compareTo(tmp.position) > 0))) {
                srt.set(j, srt.get(j - 1));
                j--;
            }
WJS
  • 36,363
  • 4
  • 24
  • 39