我得到了一个ArrayList,其中包含下一个数据:coordX、coordY、长度、位置(位置可以有3种类型:垂直、水平或1x1)。使用插入方法,我按长度降序排序。如果长度等于具有水平位置的长度值,我如何给予优先权。对于给定的输入:
(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
输出应该是:
(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
这就是我现在所拥有的:
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);
}
}
这部分代码仅负责按长度排序。
最佳答案
尝试以下操作:
您需要首先检查长度,然后如果相等,请检查位置。
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--;
}
关于java - JAVA中如何按两个条件排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61089906/