英文:
How to sort by two criteria in JAVA?
问题
我有一个包含以下数据的ArrayList:coordX,coordY,length,position(position可以是3种类型之一:vertical,horizontal或1x1)。使用插入方法,我按长度降序对其进行排序。如果长度相等,如何给予具有水平位置的长度值优先权。对于给定的输入:
(1;0),长度=2,位置-垂直
(1;6),长度=4,位置-水平
(3;4),长度=3,位置-水平
(3;6),长度=1,位置-1x1
(4;0),长度=1,位置-1x1
(5;3),长度=2,位置-水平
(6;7),长度=2,位置-垂直
(7;5),长度=2,位置-水平
输出应为:
(1;6),长度=4,位置-水平
(3;4),长度=3,位置-水平
(5;3),长度=2,位置-水平
(7;5),长度=2,位置-水平
(1;0),长度=2,位置-垂直
(6;7),长度=2,位置-垂直
(3;6),长度=1,位置-1x1
(4;0),长度=1,位置-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);
}
}
此代码部分仅负责按长度排序。
英文:
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.
答案1
得分: 1
请尝试以下内容:
您首先需要检查长度,然后如果它们相等,请检查位置。
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--;
}
英文:
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--;
}
</details>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论